Я разрабатываю службу REST с помощью SpringMVC, где у меня есть @RequestMapping на уровне класса и метода.
В настоящее время это приложение настроено на возврат jsp-страницы ошибок, настроенной в web.xml.
<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);
    }
}
