Spring MVC REST Handing Bad Url (404) by returning JSON

前端 未结 4 819
醉梦人生
醉梦人生 2021-01-30 23:56

I am developing a REST service using SpringMVC, where I have @RequestMapping at class and method level.

This application is currently configured to return error-page js

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 00:50

    If you are using Spring Boot, set BOTH of these two properties:

    spring.resources.add-mappings=false
    spring.mvc.throw-exception-if-no-handler-found=true
    

    Now your @ControllerAdvice annotated class can handle the "NoHandlerFoundException", as below.

    @ControllerAdvice
    @RequestMapping(produces = "application/json")
    @ResponseBody
    public class RestControllerAdvice {
    
        @ExceptionHandler(NoHandlerFoundException.class)
        public ResponseEntity> unhandledPath(final NoHandlerFoundException e) {
            Map errorInfo = new LinkedHashMap<>();
            errorInfo.put("timestamp", new Date());
            errorInfo.put("httpCode", HttpStatus.NOT_FOUND.value());
            errorInfo.put("httpStatus", HttpStatus.NOT_FOUND.getReasonPhrase());
            errorInfo.put("errorMessage", e.getMessage());
            return new ResponseEntity>(errorInfo, HttpStatus.NOT_FOUND);
        }
    
    }
    

    note it is not sufficient to only specify this property:

    spring.mvc.throw-exception-if-no-handler-found=true
    

    , as by default Spring maps unknown urls to /**, so there really never is "no handler found".

    To disable the unknown url mapping to /**, you need

    spring.resources.add-mappings=false ,
    

    which is why the two properties together produce the desired behavior.

提交回复
热议问题