为找不到资源创建自定义异常 404 SPRING BOOT

alg*_*mic 0 java spring spring-mvc java-8 spring-boot

我确实有一个类CustomResponseEntityExceptionHandler扩展ResponseEntityExceptionHandler了两种方法,一种用于处理错误的格式,另一种用于请求资源(url)但不存在时。我想给用户一条自定义消息,而不是 Spring 默认的白标错误页面。我试图理解为什么我的handleResourceNotFoundException方法来自CustomResponseEntityExceptionHandler当请求不存在的 URI 时不调用,而是一直显示白标签错误页面。感谢您的帮助!

\n\n
curl localhost:8080/doesnotexist\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的CustomResponseEntityExceptionHandler

\n\n
@ExceptionHandler(Exception.class)\npublic final ResponseEntity<ErrorDetails> handleAllWrongFormatExceptions(WrongFormatException ex,\n        WebRequest request) {\n    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));\n    return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);\n}\n\n@ExceptionHandler(ResourceNotFoundException.class)\npublic final ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException ex,\n        WebRequest request) {\n    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));\n    return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

用于保存自定义错误详细信息的简单类

\n\n
public class ErrorDetails {\n\nprivate Date timestamp;\nprivate String message;\nprivate String details;\n\npublic ErrorDetails(Date timestamp, String message, String details) {\n\n    this.timestamp = timestamp;\n    this.message = message;\n    this.details = details;\n}\n\npublic Date getTimestamp() {\n    return timestamp;\n}\n\npublic String getMessage() {\n    return message;\n}\n\npublic String getDetails() {\n    return details;\n}\xc2\xa0}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的控制器

\n\n
@Controller\npublic class StringManipController {\n\n@Autowired\nprivate StringProcessingService stringProcessingService;\n\n@GetMapping("/")\n@ExceptionHandler(ResourceNotFoundException.class)\n@ResponseBody\npublic String home(@RequestParam(name = "value", required = false, defaultValue = "") String value) {\n\n    return "Welcome to the String Processing Application";\n}\n\n@GetMapping("/stringDedup")\n@ResponseBody\npublic ProcessedString doManip(@RequestParam(name = "value", required = false, defaultValue = "") String value) {\n\n    String result = stringProcessingService.getStringManipulation(value);\n\n    return new ProcessedString(result);\n\n}\n\n@GetMapping("/writeNumber")\n@ResponseBody\npublic ProcessedString getWriteNumber(\n        @RequestParam(name = "value", required = false, defaultValue = "") String value) {\n\n    String number = stringProcessingService.getNumberToWords(value);\n\n    return new ProcessedString(number);\n\n} }\n
Run Code Online (Sandbox Code Playgroud)\n\n

这里的ResourceNotFoundException class

\n\n
    @ResponseStatus(HttpStatus.NOT_FOUND)\npublic class ResourceNotFoundException extends RuntimeException {\n\n\n    private static final long serialVersionUID = 266853955330077478L;\n\n    public ResourceNotFoundException(String exception) {\n        super(exception);\n    } }\n
Run Code Online (Sandbox Code Playgroud)\n

Dav*_*ujo 5

如果您使用 Spring Boot:

@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler(value = { NoHandlerFoundException.class })
    public ResponseEntity<Object> noHandlerFoundException(Exception ex) {

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("test");
    }
}
Run Code Online (Sandbox Code Playgroud)

或者

@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(
            NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        return handleExceptionInternal(ex, "Test", headers, status, request);
    }
}
Run Code Online (Sandbox Code Playgroud)

类中org.springframework.web.servlet.DispatcherServlet有一个名为 的变量throwExceptionIfNoHandlerFound。如果将其设置为true调用的方法,noHandlerFound则会抛出NoHandlerFoundException. 您的异常处理程序现在将捕获它。

将此属性添加到您的application.properties文件中:spring.mvc.throw-exception-if-no-handler-found=true