Spring Boot-自定义异常处理程序 [英] Spring boot - custom exceptions handler
问题描述
我正在使用Spring Boot开发一个rest应用程序。
此应用程序有一个自定义过滤器,仅允许在某些请求下访问。
如果用户需要特定资源,则过滤器将引发异常。
如何在全局级别处理此过滤器中生成的所有异常?
I'm developing a rest application with Spring boot. This application have a custom filter that allows access, only, at some requests. If the user require a particular resource the filter throw an exception. how can I handle all the exceptions generated in this filter at the global level?
我已经尝试过 @ControllerAdvice
批注但不起作用。
I have tried the @ControllerAdvice
annotation but not working.
推荐答案
首先,您可能具有自定义的Exception Handler类,它将替换默认
First of all you may have your customized Exception Handler class, it will replace the default
ResponseEntityExceptionHandler
下面是我在学习期间使用的一个示例代码:
Below is one sample code I used during my studies:
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), "Validation Failed", ex.getBindingResult().toString());
return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST);
}
}
然后您可以添加自定义的例外并补充响应
You can then add your customized Exceptions and complement the response object if you need it.
请在此处
这篇关于Spring Boot-自定义异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!