简体   繁体   English

为找不到资源创建自定义例外404 SPRING BOOT

[英]Creating Custom Exception for Resource Not Found 404 SPRING BOOT

I do have a class CustomResponseEntityExceptionHandler class extending ResponseEntityExceptionHandler with 2 methods one for handling wrong formats and the other one when a resource (url) is requested but does not exist. 我确实有一个CustomResponseEntityExceptionHandler类,该类使用2种方法扩展ResponseEntityExceptionHandler ,一种用于处理错误的格式,另一种用于在请求资源(url)但不存在时进行处理。 I would like to give the user a custom message instead of the default White Label Error page of Spring. 我想给用户一个自定义消息,而不是Spring的默认“白色标签错误”页面。 I'm trying to understand why my handleResourceNotFoundException method from CustomResponseEntityExceptionHandler is not called when a non existing URI is requested but instead I keep having the White Label Error page. 我试图了解为什么当请求不存在的URI时不调用CustomResponseEntityExceptionHandler handleResourceNotFoundException方法,而是保持白色标签错误页面的原因。 Thanks for your help! 谢谢你的帮助!

curl localhost:8080/doesnotexist

This is my CustomResponseEntityExceptionHandler 这是我的CustomResponseEntityExceptionHandler

@ExceptionHandler(Exception.class)
public final ResponseEntity<ErrorDetails> handleAllWrongFormatExceptions(WrongFormatException ex,
        WebRequest request) {
    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));
    return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(ResourceNotFoundException.class)
public final ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException ex,
        WebRequest request) {
    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
    return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}

Simple class for holding custom error details 用于保存自定义错误详细信息的简单类

public class ErrorDetails {

private Date timestamp;
private String message;
private String details;

public ErrorDetails(Date timestamp, String message, String details) {

    this.timestamp = timestamp;
    this.message = message;
    this.details = details;
}

public Date getTimestamp() {
    return timestamp;
}

public String getMessage() {
    return message;
}

public String getDetails() {
    return details;
} }

And here is my controller 这是我的控制器

@Controller
public class StringManipController {

@Autowired
private StringProcessingService stringProcessingService;

@GetMapping("/")
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseBody
public String home(@RequestParam(name = "value", required = false, defaultValue = "") String value) {

    return "Welcome to the String Processing Application";
}

@GetMapping("/stringDedup")
@ResponseBody
public ProcessedString doManip(@RequestParam(name = "value", required = false, defaultValue = "") String value) {

    String result = stringProcessingService.getStringManipulation(value);

    return new ProcessedString(result);

}

@GetMapping("/writeNumber")
@ResponseBody
public ProcessedString getWriteNumber(
        @RequestParam(name = "value", required = false, defaultValue = "") String value) {

    String number = stringProcessingService.getNumberToWords(value);

    return new ProcessedString(number);

} }

And here the ResourceNotFoundException class 这里是ResourceNotFoundException class

    @ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {


    private static final long serialVersionUID = 266853955330077478L;

    public ResourceNotFoundException(String exception) {
        super(exception);
    } }

If you used Spring Boot: 如果您使用Spring Boot:

@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

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

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("test");
    }
}

or 要么

@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);
    }
}

In the org.springframework.web.servlet.DispatcherServlet class there is a variable called throwExceptionIfNoHandlerFound . org.springframework.web.servlet.DispatcherServlet类中,有一个名为throwExceptionIfNoHandlerFound的变量。 If this is set to true a method called noHandlerFound will throw a NoHandlerFoundException . 如果将其设置为true名为noHandlerFound的方法将抛出NoHandlerFoundException Your exception handler will now catch it. 您的异常处理程序现在将捕获它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM