我正在開發一個使用SpringMVC的REST服務,其中我在類和方法級別具有@RequestMapping。Spring MVC REST通過返回JSON處理Bad Url(404)
此應用程序當前配置爲返回web.xml中配置的錯誤頁面jsp。
<error-page>
<error-code>404</error-code>
<location>/resourceNotFound</location>
</error-page>
但是我想返回自定義JSON而不是這個錯誤頁面。
我能夠處理異常並返回json的其他異常,通過寫在控制器中,但不知道如何編寫邏輯返回JSON時根本不存在的URL。
@ExceptionHandler(TypeMismatchException.class)
@ResponseStatus(value=HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseEntity<String> handleTypeMismatchException(HttpServletRequest req, TypeMismatchException ex) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
Locale locale = LocaleContextHolder.getLocale();
String errorMessage = messageSource.getMessage("error.patient.bad.request", null, locale);
errorMessage += ex.getValue();
String errorURL = req.getRequestURL().toString();
ErrorInfo errorInfo = new ErrorInfo(errorURL, errorMessage);
return new ResponseEntity<String>(errorInfo.toJson(), headers, HttpStatus.BAD_REQUEST);
}
我試過@ControllerAdvice,它適用於其他異常的情況,而不是在映射不avaialble,
@ControllerAdvice
public class RestExceptionProcessor {
@Autowired
private MessageSource messageSource;
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(value=HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseEntity<String> requestMethodNotSupported(HttpServletRequest req, HttpRequestMethodNotSupportedException ex) {
Locale locale = LocaleContextHolder.getLocale();
String errorMessage = messageSource.getMessage("error.patient.bad.id", null, locale);
String errorURL = req.getRequestURL().toString();
ErrorInfo errorInfo = new ErrorInfo(errorURL, errorMessage);
return new ResponseEntity<String>(errorInfo.toJson(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
@ResponseStatus(value=HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseEntity<String> requestHandlingMethodNotSupported(HttpServletRequest req, NoSuchRequestHandlingMethodException ex) {
Locale locale = LocaleContextHolder.getLocale();
String errorMessage = messageSource.getMessage("error.patient.bad.id", null, locale);
String errorURL = req.getRequestURL().toString();
ErrorInfo errorInfo = new ErrorInfo(errorURL, errorMessage);
return new ResponseEntity<String>(errorInfo.toJson(), HttpStatus.BAD_REQUEST);
}
}
優秀的答案,值得注意的是,你不能使用[DefaultServletHandlerConfigurer](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/ DefaultServletHandlerConfigurer.html),因爲在獲取到DispatcherServlet之前會消耗404個郵箱 – muttonUp
我試過這種方法,我希望實現HandlerExceptionResolver的解析器能夠捕獲此異常,但事實並非如此。 – user2807219
對於基於java的配置,您需要覆蓋'AbstractAnnotationConfigDispatcherServletInitializer'的'customizeRegistration'。看[這個答案](http://stackoverflow.com/a/22751886/878514)。 – fracz