【问题标题】:Optimize Spring RestControllerAdvice with multiple exceptions使用多个异常优化 Spring RestControllerAdvice
【发布时间】:2019-12-02 19:04:52
【问题描述】:

我有大约 20 到 30 种不同类型的不同异常,它们都扩展了 Java 中的异常类。 一个例子是:

public class NoHandlerFoundException extends Exception {

private static final long serialVersionUID = -9079454849611061074L;

public NoHandlerFoundException() {
    super();
}

public NoHandlerFoundException(final String message) {
    super(message);
}

}

其他例子是:

public class ResourceNotFoundException extends Exception{

private static final long serialVersionUID = -9079454849611061074L;

public ResourceNotFoundException() {
    super();
}

public ResourceNotFoundException(final String message) {
    super(message);
}

}

还有更多。 如您所见,大部分代码都是重复的,然后我使用 ControllerAdvice 之类的(我知道 ControllerAdvice 参数异常类中的代码应该是正确的):

@ExceptionHandler({NoHandlerFoundException.class, ResourceNotFoundException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public @ResponseBody ExceptionResponse handleResourceNotFound(final NoHandlerFoundException exception,
        final HttpServletRequest request) {

    ExceptionResponse error = new ExceptionResponse();
    error.setErrorMessage(exception.getMessage());
    error.callerURL(request.getRequestURI());

    return error;
}

所以我想知道我们是否有任何方法可以优化上述异常,而不是编写单个类执行几乎相同的工作 n 次,但仍想区分它们。 谢谢。

【问题讨论】:

    标签: java spring-boot exception controller-advice


    【解决方案1】:

    您可以使用以下方法来减少代码冗余。

        @ExceptionHandler(value = {NoHandlerFoundException.class, ResourceNotFoundException.class})
    protected ResponseEntity handleInvalidDataException(RuntimeException exception, WebRequest request) {
    
        ExceptionResponse error = new ExceptionResponse();
        error.setErrorMessage(exception.getMessage());
        error.callerURL(request.getRequestURI());
    
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2018-01-04
      • 1970-01-01
      • 2020-11-13
      • 2019-06-02
      • 2019-05-05
      • 2011-08-26
      • 1970-01-01
      • 2019-02-22
      相关资源
      最近更新 更多