简体   繁体   English

Spring Boot-自定义异常处理程序

[英]Spring boot - custom exceptions handler

I'm developing a rest application with Spring boot. 我正在使用Spring Boot开发一个Rest应用程序。 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? 如何在全局级别处理此过滤器中生成的所有异常?

I have tried the @ControllerAdvice annotation but not working. 我已经尝试了@ControllerAdvice批注,但是没有用。

at the first, you should create a custom exception and extend it from runtimeException 首先,您应该创建一个自定义异常并将其从runtimeException扩展

public class CustomException extends RuntimeException
{
    ...
}

and then you can catch it like this 然后你可以像这样抓住它

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ResponseEntity handleCustomException(CustomException ex) {
          return ResponseHelper.response(ex.getData(), ex.getMsg(), 
         ex.getStatus());
        }
}

First of all you may have your customized Exception Handler class, it will replace the default 首先,您可能具有自定义的Exception Handler类,它将替换默认的

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. 然后,您可以添加自定义的异常,并在需要时补充响应对象。

Please find the complete code with the other classes over here 请在此处找到其他类的完整代码

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

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