简体   繁体   English

Spring Boot @ExceptionHandlers 如何拦截异常

[英]How do Spring Boot @ExceptionHandlers intercept exceptions

Lets say we have a post mapping for example that creates and returns a person object and its request body provides a first and last name that are both primary keys for some database.例如,假设我们有一个 post 映射,它创建并返回一个 person 对象,它的请求正文提供了名字和姓氏,它们都是某些数据库的主键。 If either value is null then an exception is thrown.如果任一值为 null,则引发异常。

Assuming we have another controller set up to handle the exception and intercept it with the @controlleradvice and @exceptionhandler annotations and a method that returns a ResponseEntity How does it actually intercept the exception and why does the return type of the handler not have to match the return type of the post method that threw it.假设我们设置了另一个控制器来处理异常并使用 @controlleradvice 和 @exceptionhandler 注释以及返回 ResponseEntity 的方法拦截它 它实际上如何拦截异常以及为什么处理程序的返回类型不必匹配抛出它的 post 方法的返回类型。 Sorry if it is a silly question, i just cant seem to grasp it.抱歉,如果这是一个愚蠢的问题,我似乎无法理解。 I would like to understand whats happening behind the scenes.我想了解幕后发生的事情。

I understand what the annotations do and hiw we specify what exception to handle, I just dont understand the how我了解注释的作用以及我们指定要处理的异常,我只是不明白如何

ExceptionHandler is pointcut aspects in spring's aspect oriented programming terminologies. ExceptionHandler是 Spring 面向方面的编程术语中的切入点方面。

As per pointcut doc:根据切入点文档:

Pointcut: a predicate that matches join points.切入点:匹配连接点的谓词。 Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name) Advice 与切入点表达式相关联,并在与切入点匹配的任何连接点处运行(例如,执行具有特定名称的方法)

We define type of exception in ExceptionHandler annotation(ie Exception.class etc) .我们在ExceptionHandler注释中定义异常类型(即Exception.class等)。 Jointpoint aspect in this case is handling exception thrown by advice's (here ControllerAdvice ) method.在这种情况下,Jointpoint 方面是处理通知(此处为ControllerAdvice )方法引发的异常。

When exception occurred in advice's method, you are supposed to throw that exception & your spring advice intercept that exception & pass control to pointcut which then matches exception type & do its handling.当通知的方法中发生异常时,您应该抛出该异常并且您的弹簧建议拦截该异常并将控制传递给切入点,然后匹配异常类型并进行处理。

Regarding method signature of ExceptionHandler , doc says its flexible & hence it is not strict to return type of post method you defined.关于ExceptionHandler的方法签名, 文档说它很灵活,因此返回您定义的 post 方法的类型并不严格。

Reference 参考

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

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