![](/img/trans.png)
[英]Spring Boot @RestControllerAdvice not Catching Custom Exceptions
[英]Optimize Spring RestControllerAdvice with multiple exceptions
我有大约20到30种不同类型的不同Exception,它们都在Java中扩展了Exception类。 一个例子是:
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次几乎相同的工作,但仍希望区分它们。 谢谢。
您可以使用以下方法来减少代码冗余。
@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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.