版本說明:Spring Boot 2.0.1.RELEASE
REST風格默認的404響應如下:
{
"timestamp": "2018-06-07T05:23:27.196+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/shopping/123/TEST"
}
如果不想返回此內容,需要做如下配置:
application.yml
spring:
mvc:
throw-exception-if-no-handler-found: true
resources:
add-mappings: false
添加以上配置后,404時DispatcherServlet
會拋出NoHandlerFoundException
,注意spring.resources.add-mappings
在當前版本下需要設置為false,否則不會拋出異常。
異常捕獲
在項目中我使用了全局異常處理,如下:
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {Exception.class})
public ResponseEntity<Object> handleExceptions(Exception ex, WebRequest request) {
logger.error("Exception", ex);
mailPublisher.publishMailToAdministrator(ex);
return handleExceptionInternal(ex, RESPONSE_ERROR, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
/**
* Handle NoHandlerFoundException
* @param ex
* @param headers
* @param status
* @param request
* @return
*/
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, RESPONSE_ERROR, headers, status, request);
}
}
重寫ResponseEntityExceptionHandler
的handleNoHandlerFoundException方法來處理404異常,注意不要在全局異常處理中添加如下方法:
@ExceptionHandler(value = {NoHandlerFoundException.class})
public ResponseEntity<Object> handleNotFoundExceptions(NoHandlerFoundException ex) {
return handleExceptionInternal(ex, RESPONSE_ERROR, new HttpHeaders(), HttpStatus.NOT_FOUND, null);
}
否則會拋出如下異常,因為ResponseEntityExceptionHandler.handleException已經注冊了對該異常的處理,如果我們再注冊一個,會有兩個異常處理,導致Ambiguous。
Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.servlet.NoHandlerFoundException]