您可以扩展 ResponseEntityExceptionHandler 类,其中包含 Spring Boot 项目中的许多常见异常。例如,如果您希望使用自定义处理程序来绑定异常,则可以使用以下内容,
@ControllerAdvice
public class MyApiExceptionHandler extends ResponseEntityExceptionHandler {
@Override
public ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String responseBody = "{\"key\":\"value\"}";
headers.add("Content-Type", "application/json;charset=utf-8");
return handleExceptionInternal(ex, responseBody, headers, HttpStatus.NOT_ACCEPTABLE, request);
}
}
http 状态的另一个示例404-未找到,
@ControllerAdvice
public class MyApiExceptionHandler extends ResponseEntityExceptionHandler {
@Override
public ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String responseBody = "{\"errormessage\":\"WHATEVER YOU LIKE\"}";
headers.add("Content-Type", "application/json;charset=utf-8");
return handleExceptionInternal(ex, responseBody, headers, HttpStatus.NOT_FOUND, request);
}
}
关于 404 not found 异常,您应该将 DispatcherServlet 配置为在找不到任何处理程序时抛出异常,而不是默认行为。对于 404 的问题,你也可以阅读this question。