我正在尝试建立一个大型 REST 服务服务器。我们使用的是 Spring Boot 1.2.1 Spring 4.1.5 和 Java 8。我们的控制器正在实现 @RestController 和标准的 @RequestMapping 注解。
我的问题是 Spring Boot 为控制器异常设置了默认重定向到 /error
。从文档:
Spring Boot 默认提供了一个 /error 映射,它以一种合理的方式处理所有错误,并且它在 servlet 容器中注册为一个“全局”错误页面。
多年来使用 Node.js 编写 REST 应用程序,对我来说,这绝不是明智之举。服务端点生成的任何异常都应在响应中返回。我不明白您为什么要将重定向发送给最有可能只是在寻找答案并且不能或不会对重定向采取任何操作的 Angular 或 JQuery SPA 消费者。
我想要做的是设置一个可以接受任何异常的全局错误处理程序 - 有目的地从请求映射方法抛出或由 Spring 自动生成(如果没有找到请求路径签名的处理程序方法,则为 404),并返回一个没有任何 MVC 重定向的客户端的标准格式错误响应(400、500、503、404)。具体来说,我们将获取错误,使用 UUID 将其记录到 NoSQL,然后使用 JSON 正文中日志条目的 UUID 将正确的 HTTP 错误代码返回给客户端。
文档对如何执行此操作含糊不清。在我看来,您必须创建自己的 ErrorController 实现或以某种方式使用 ControllerAdvice,但我看到的所有示例仍然包括将响应转发到某种错误映射,这无济于事.其他示例建议您必须列出要处理的每个异常类型,而不是仅列出“可抛出”并获取所有内容。
谁能告诉我我错过了什么,或者在不建议 Node.js 更容易处理的链条的情况下为我指出如何做到这一点的正确方向?
新答案 (2016-04-20)
使用 Spring Boot 1.3.1.RELEASE
新的第 1 步 - 将以下属性添加到 application.properties 很容易且侵入性较小:
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
比修改现有的 DispatcherServlet 实例(如下)容易得多! - 乔'
如果使用完整的 RESTful 应用程序,禁用静态资源的自动映射非常重要,因为如果您使用 Spring Boot 的默认配置来处理静态资源,那么资源处理程序将处理请求(它最后排序并映射到 / ** 这意味着它会拾取应用程序中任何其他处理程序未处理的任何请求),因此调度程序 servlet 没有机会抛出异常。
新答案 (2015-12-04)
使用 Spring Boot 1.2.7.RELEASE
新的第 1 步 - 我发现了一种设置“throExceptionIfNoHandlerFound”标志的侵入性要小得多的方法。在应用程序初始化类中将下面的 DispatcherServlet 替换代码(步骤 1)替换为:
@ComponentScan()
@EnableAutoConfiguration
public class MyApplication extends SpringBootServletInitializer {
private static Logger LOG = LoggerFactory.getLogger(MyApplication.class);
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet");
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
}
在这种情况下,我们在现有的 DispatcherServlet 上设置标志,它保留了 Spring Boot 框架的任何自动配置。
我发现的另一件事 - @EnableWebMvc 注释对 Spring Boot 来说是致命的。是的,该注解可以像下面描述的那样捕获所有控制器异常,但它也扼杀了 Spring Boot 通常会提供的许多有用的自动配置。使用 Spring Boot 时要格外小心地使用该注释。
原答案:
经过大量研究和跟进此处发布的解决方案(感谢您的帮助!)以及对 Spring 代码的大量运行时跟踪,我终于找到了一个可以处理所有异常的配置(不是错误,但请继续阅读)包括404。
第 1 步 - 告诉 SpringBoot 在“找不到处理程序”的情况下停止使用 MVC。我们希望 Spring 抛出异常,而不是向客户端返回重定向到“/error”的视图。为此,您需要在您的配置类之一中有一个条目:
// NEW CODE ABOVE REPLACES THIS! (2015-12-04)
@Configuration
public class MyAppConfig {
@Bean // Magic entry
public DispatcherServlet dispatcherServlet() {
DispatcherServlet ds = new DispatcherServlet();
ds.setThrowExceptionIfNoHandlerFound(true);
return ds;
}
}
这样做的缺点是它替换了默认的调度程序 servlet。这对我们来说还不是问题,没有出现副作用或执行问题。如果您出于其他原因要对调度程序 servlet 执行任何其他操作,那么这里就是执行这些操作的地方。
第 2 步 - 现在 spring boot 将在找不到处理程序时抛出异常,该异常可以与统一异常处理程序中的任何其他异常一起处理:
@EnableWebMvc
@ControllerAdvice
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Throwable.class)
@ResponseBody
ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
ErrorResponse errorResponse = new ErrorResponse(ex);
if(ex instanceof ServiceException) {
errorResponse.setDetails(((ServiceException)ex).getDetails());
}
if(ex instanceof ServiceHttpException) {
return new ResponseEntity<Object>(errorResponse,((ServiceHttpException)ex).getStatus());
} else {
return new ResponseEntity<Object>(errorResponse,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String,String> responseBody = new HashMap<>();
responseBody.put("path",request.getContextPath());
responseBody.put("message","The URL you have reached is not in service at this time (404).");
return new ResponseEntity<Object>(responseBody,HttpStatus.NOT_FOUND);
}
...
}
请记住,我认为“@EnableWebMvc”注释在这里很重要。似乎没有它,这一切都行不通。就是这样 - 您的 Spring boot 应用程序现在将捕获上述处理程序类中的所有异常,包括 404,您可以随意处理它们。
最后一点 - 似乎没有办法让它捕捉抛出的错误。我有一个古怪的想法,即使用方面来捕获错误并将它们转换为上面的代码可以处理的异常,但我还没有时间实际尝试实现它。希望这可以帮助某人。
任何评论/更正/增强将不胜感激。
在 Spring Boot 1.4+ 中,添加了用于更轻松处理异常的新酷类,这有助于删除样板代码。
为异常处理提供了一个新的 @RestControllerAdvice
,它是 @ControllerAdvice
和 @ResponseBody
的组合。使用此新注释时,您可以删除 @ExceptionHandler
方法上的 @ResponseBody
。
IE
@RestControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(value = { Exception.class })
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiErrorResponse unknownException(Exception ex, WebRequest req) {
return new ApiErrorResponse(...);
}
}
为了处理 404 错误,将 @EnableWebMvc
注释和以下内容添加到 application.properties 就足够了:
spring.mvc.throw-exception-if-no-handler-found=true
您可以在此处找到并使用源代码:
https://github.com/magiccrafter/spring-boot-exception-handling
@RestControllerAdvice
处理所有异常而无需额外配置。我在这里想念什么?
我认为 ResponseEntityExceptionHandler
符合您的要求。 HTTP 400 的示例代码:
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentNotValidException.class,
HttpRequestMethodNotSupportedException.class})
public ResponseEntity<Object> badRequest(HttpServletRequest req, Exception exception) {
// ...
}
}
您可以查看此post
HttpRequestMethodNotSupportedException
并在多个微服务中插入相同的 jar,出于某些业务目的,我们需要在响应中响应微服务别名。有什么方法可以获取底层微服务名称/控制器名称?我知道 HandlerMethod
将提供引发异常的 java 方法名称。但是在这里,没有一个方法收到请求,因此 HandlerMethod
不会被初始化。那么有什么办法可以解决这个问题吗?
虽然这是一个较老的问题,但我想分享我对此的想法。我希望它对你们中的一些人有所帮助。
我目前正在构建一个 REST API,它使用 Spring Boot 1.5.2.RELEASE 和 Spring Framework 4.3.7.RELEASE。我使用 Java Config 方法(与 XML 配置相反)。此外,我的项目使用 @RestControllerAdvice
注释使用全局异常处理机制(见下文)。
我的项目与您的项目具有相同的要求:当我的 REST API 尝试向不存在的 URL 发送请求时,我希望我的 REST API 在对 API 客户端的 HTTP 响应中返回一个带有随附 JSON 有效负载的 HTTP 404 Not Found
。在我的例子中,JSON 有效负载看起来像这样(这明显不同于 Spring Boot 默认值,顺便说一句。):
{
"code": 1000,
"message": "No handler found for your request.",
"timestamp": "2017-11-20T02:40:57.628Z"
}
我终于让它工作了。以下是您需要完成的主要任务:
如果 API 客户端调用不存在处理程序方法的 URL,请确保抛出 NoHandlerFoundException(请参阅下面的步骤 1)。
创建一个自定义错误类(在我的例子中为 ApiError),其中包含应返回给 API 客户端的所有数据(参见步骤 2)。
创建一个异常处理程序,该处理程序对 NoHandlerFoundException 做出反应并向 API 客户端返回正确的错误消息(请参见步骤 3)。
为它编写一个测试并确保它可以工作(参见第 4 步)。
好的,现在进入细节:
第 1 步:配置 application.properties
我必须将以下两个配置设置添加到项目的 application.properties
文件中:
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
这样可以确保在客户端尝试访问不存在能够处理请求的控制器方法的 URL 的情况下抛出 NoHandlerFoundException
。
第 2 步:为 API 错误创建一个类
我在 Eugen Paraschiv 的博客上创建了一个类似于 this article 中建议的课程。此类表示 API 错误。如果出现错误,此信息将在 HTTP 响应正文中发送给客户端。
public class ApiError {
private int code;
private String message;
private Instant timestamp;
public ApiError(int code, String message) {
this.code = code;
this.message = message;
this.timestamp = Instant.now();
}
public ApiError(int code, String message, Instant timestamp) {
this.code = code;
this.message = message;
this.timestamp = timestamp;
}
// Getters and setters here...
}
第 3 步:创建/配置全局异常处理程序
我使用以下类来处理异常(为简单起见,我删除了导入语句、日志记录代码和其他一些不相关的代码):
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiError noHandlerFoundException(
NoHandlerFoundException ex) {
int code = 1000;
String message = "No handler found for your request.";
return new ApiError(code, message);
}
// More exception handlers here ...
}
第 4 步:编写测试
我想确保 API 始终向调用客户端返回正确的错误消息,即使在失败的情况下也是如此。因此,我写了一个这样的测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SprintBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class GlobalExceptionHandlerIntegrationTest {
public static final String ISO8601_DATE_REGEX =
"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$";
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(roles = "DEVICE_SCAN_HOSTS")
public void invalidUrl_returnsHttp404() throws Exception {
RequestBuilder requestBuilder = getGetRequestBuilder("/does-not-exist");
mockMvc.perform(requestBuilder)
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.code", is(1000)))
.andExpect(jsonPath("$.message", is("No handler found for your request.")))
.andExpect(jsonPath("$.timestamp", RegexMatcher.matchesRegex(ISO8601_DATE_REGEX)));
}
private RequestBuilder getGetRequestBuilder(String url) {
return MockMvcRequestBuilders
.get(url)
.accept(MediaType.APPLICATION_JSON);
}
@ActiveProfiles("dev")
注释可以省略。我只在使用不同的配置文件时使用它。 RegexMatcher
是我用来更好地处理时间戳字段的自定义 Hamcrest matcher。这是代码(我找到它 here):
public class RegexMatcher extends TypeSafeMatcher<String> {
private final String regex;
public RegexMatcher(final String regex) {
this.regex = regex;
}
@Override
public void describeTo(final Description description) {
description.appendText("matches regular expression=`" + regex + "`");
}
@Override
public boolean matchesSafely(final String string) {
return string.matches(regex);
}
// Matcher method you can call on this matcher class
public static RegexMatcher matchesRegex(final String string) {
return new RegexMatcher(regex);
}
}
我这边的一些进一步说明:
在 StackOverflow 上的许多其他帖子中,人们建议设置 @EnableWebMvc 注释。在我的情况下,这不是必需的。
这种方法适用于 MockMvc(见上面的测试)。
这段代码呢?我使用回退请求映射来捕获 404 错误。
@Controller
@ControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
//If exception has a ResponseStatus annotation then use its response code
ResponseStatus responseStatusAnnotation = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);
return buildModelAndViewErrorPage(request, response, ex, responseStatusAnnotation != null ? responseStatusAnnotation.value() : HttpStatus.INTERNAL_SERVER_ERROR);
}
@RequestMapping("*")
public ModelAndView fallbackHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
return buildModelAndViewErrorPage(request, response, null, HttpStatus.NOT_FOUND);
}
private ModelAndView buildModelAndViewErrorPage(HttpServletRequest request, HttpServletResponse response, Exception ex, HttpStatus httpStatus) {
response.setStatus(httpStatus.value());
ModelAndView mav = new ModelAndView("error.html");
if (ex != null) {
mav.addObject("title", ex);
}
mav.addObject("content", request.getRequestURL());
return mav;
}
}
@RestControllerAdvice 是 Spring Framework 4.3 的一项新功能,通过横切关注解决方案使用 RestfulApi 处理异常:
package com.khan.vaquar.exception;
import javax.servlet.http.HttpServletRequest;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.khan.vaquar.domain.ErrorResponse;
/**
* Handles exceptions raised through requests to spring controllers.
**/
@RestControllerAdvice
public class RestExceptionHandler {
private static final String TOKEN_ID = "tokenId";
private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class);
/**
* Handles InstructionExceptions from the rest controller.
*
* @param e IntrusionException
* @return error response POJO
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = IntrusionException.class)
public ErrorResponse handleIntrusionException(HttpServletRequest request, IntrusionException e) {
log.warn(e.getLogMessage(), e);
return this.handleValidationException(request, new ValidationException(e.getUserMessage(), e.getLogMessage()));
}
/**
* Handles ValidationExceptions from the rest controller.
*
* @param e ValidationException
* @return error response POJO
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = ValidationException.class)
public ErrorResponse handleValidationException(HttpServletRequest request, ValidationException e) {
String tokenId = request.getParameter(TOKEN_ID);
log.info(e.getMessage(), e);
if (e.getUserMessage().contains("Token ID")) {
tokenId = "<OMITTED>";
}
return new ErrorResponse( tokenId,
HttpStatus.BAD_REQUEST.value(),
e.getClass().getSimpleName(),
e.getUserMessage());
}
/**
* Handles JsonProcessingExceptions from the rest controller.
*
* @param e JsonProcessingException
* @return error response POJO
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = JsonProcessingException.class)
public ErrorResponse handleJsonProcessingException(HttpServletRequest request, JsonProcessingException e) {
String tokenId = request.getParameter(TOKEN_ID);
log.info(e.getMessage(), e);
return new ErrorResponse( tokenId,
HttpStatus.BAD_REQUEST.value(),
e.getClass().getSimpleName(),
e.getOriginalMessage());
}
/**
* Handles IllegalArgumentExceptions from the rest controller.
*
* @param e IllegalArgumentException
* @return error response POJO
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = IllegalArgumentException.class)
public ErrorResponse handleIllegalArgumentException(HttpServletRequest request, IllegalArgumentException e) {
String tokenId = request.getParameter(TOKEN_ID);
log.info(e.getMessage(), e);
return new ErrorResponse( tokenId,
HttpStatus.BAD_REQUEST.value(),
e.getClass().getSimpleName(),
e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = UnsupportedOperationException.class)
public ErrorResponse handleUnsupportedOperationException(HttpServletRequest request, UnsupportedOperationException e) {
String tokenId = request.getParameter(TOKEN_ID);
log.info(e.getMessage(), e);
return new ErrorResponse( tokenId,
HttpStatus.BAD_REQUEST.value(),
e.getClass().getSimpleName(),
e.getMessage());
}
/**
* Handles MissingServletRequestParameterExceptions from the rest controller.
*
* @param e MissingServletRequestParameterException
* @return error response POJO
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MissingServletRequestParameterException.class)
public ErrorResponse handleMissingServletRequestParameterException( HttpServletRequest request,
MissingServletRequestParameterException e) {
String tokenId = request.getParameter(TOKEN_ID);
log.info(e.getMessage(), e);
return new ErrorResponse( tokenId,
HttpStatus.BAD_REQUEST.value(),
e.getClass().getSimpleName(),
e.getMessage());
}
/**
* Handles NoHandlerFoundExceptions from the rest controller.
*
* @param e NoHandlerFoundException
* @return error response POJO
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(value = NoHandlerFoundException.class)
public ErrorResponse handleNoHandlerFoundException(HttpServletRequest request, NoHandlerFoundException e) {
String tokenId = request.getParameter(TOKEN_ID);
log.info(e.getMessage(), e);
return new ErrorResponse( tokenId,
HttpStatus.NOT_FOUND.value(),
e.getClass().getSimpleName(),
"The resource " + e.getRequestURL() + " is unavailable");
}
/**
* Handles all remaining exceptions from the rest controller.
*
* This acts as a catch-all for any exceptions not handled by previous exception handlers.
*
* @param e Exception
* @return error response POJO
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = Exception.class)
public ErrorResponse handleException(HttpServletRequest request, Exception e) {
String tokenId = request.getParameter(TOKEN_ID);
log.error(e.getMessage(), e);
return new ErrorResponse( tokenId,
HttpStatus.INTERNAL_SERVER_ERROR.value(),
e.getClass().getSimpleName(),
"An internal error occurred");
}
}
默认情况下,Spring Boot 会提供带有错误详细信息的 json。
curl -v localhost:8080/greet | json_pp
[...]
< HTTP/1.1 400 Bad Request
[...]
{
"timestamp" : 1413313361387,
"exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
"status" : 400,
"error" : "Bad Request",
"path" : "/greet",
"message" : "Required String parameter 'name' is not present"
}
它也适用于所有类型的请求映射错误。查看这篇文章http://www.jayway.com/2014/10/19/spring-boot-error-responses/
如果你想创建日志到 NoSQL。您可以创建 @ControllerAdvice 来记录它,然后重新抛出异常。文档中有示例 https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
对于 REST 控制器,我建议使用 Zalando Problem Spring Web
。
https://github.com/zalando/problem-spring-web
如果 Spring Boot 旨在嵌入一些自动配置,那么这个库在异常处理方面做得更多。您只需要添加依赖项:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web</artifactId>
<version>LATEST</version>
</dependency>
然后为您的异常定义一个或多个建议特征(或使用默认提供的那些)
public interface NotAcceptableAdviceTrait extends AdviceTrait {
@ExceptionHandler
default ResponseEntity<Problem> handleMediaTypeNotAcceptable(
final HttpMediaTypeNotAcceptableException exception,
final NativeWebRequest request) {
return Responses.create(Status.NOT_ACCEPTABLE, exception, request);
}
}
然后,您可以将异常处理的控制器建议定义为:
@ControllerAdvice
class ExceptionHandling implements MethodNotAllowedAdviceTrait, NotAcceptableAdviceTrait {
}
对于想要根据http状态码响应的人,可以使用ErrorController
方式:
@Controller
public class CustomErrorController extends BasicErrorController {
public CustomErrorController(ServerProperties serverProperties) {
super(new DefaultErrorAttributes(), serverProperties.getError());
}
@Override
public ResponseEntity error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status.equals(HttpStatus.INTERNAL_SERVER_ERROR)){
return ResponseEntity.status(status).body(ResponseBean.SERVER_ERROR);
}else if (status.equals(HttpStatus.BAD_REQUEST)){
return ResponseEntity.status(status).body(ResponseBean.BAD_REQUEST);
}
return super.error(request);
}
}
这里的 ResponseBean
是我用于响应的自定义 pojo。
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
和 @EnableWebMvc @ControllerAdvice
的解决方案适用于 Spring Boot 1.3.1,但不适用于 1.2.7
带有 RestController Annotation 的简单异常控制器类将负责控制器级别的异常处理。
@RestControllerAdvice
public class ExceptionController
{
// Mention the exception here..
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity<?> exceptionHandler(MethodArgumentNotValidException e)
{
var errors = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
var response = new ResponseBuilder()
.withHttpStatus(HttpStatus.BAD_REQUEST.value())
.withMessage(CustomStatus.FAILED.getMessage())
.withErrorCode(CustomStatus.FAILED.getValue())
.withErrorDescription(errors)
.build();
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
}
不定期副业成功案例分享
@ControllerAdvice
类时,我什至没有调用任何@ExceptionHandler
方法,尽管如果将它们放入@RestController
类中它们可以正常工作。@EnableWebMvc
在@ControllerAdvice
和@Configuration
(我测试了每个组合)类上。任何想法或工作示例? //@安迪威尔金森