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

时间:2018-10-31 13:13:06

标签: java spring spring-mvc spring-boot java-8

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

curl localhost:8080/doesnotexist

这是我的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);
}

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

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

这是我的控制器

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

} }

这里是ResourceNotFoundException class

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


    private static final long serialVersionUID = 266853955330077478L;

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

1 个答案:

答案 0 :(得分:2)

如果您使用的是Spring Boot:

@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

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

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

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

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

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