Spring Boot @ExceptionHandlers如何拦截异常

发布于 2025-02-13 21:02:41 字数 276 浏览 3 评论 0 原文

假设我们有一个帖子映射,例如创建并返回一个人对象,其请求主体提供了一个和姓氏,都是某些数据库的主要键。如果两个值为null,则会引发异常。

假设我们设置了另一个控制器来处理异常,并使用@controllerAdvice和@exceptionhandler注释以及返回响应率的方法如何实际拦截异常,以及为什么处理程序的返回类型不必匹配该响应的方法将其扔掉的邮政方法的返回类型。抱歉,如果这是一个愚蠢的问题,我似乎无法掌握它。我想了解幕后发生的事情。

我了解注释的作用,并且您指定要处理的例外,我只是不了解如何处理

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. If either value is null then an exception is thrown.

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. 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

病毒体 2025-02-20 21:02:41

exceptionhandler 是春季面向的编程术语中的点刻表方面。

按照点刻表:

尖端:与联接点匹配的谓词。建议相关
带有尖端表达式,并在任何结合点上运行
尖端(例如,执行具有特定名称的方法)

我们在 exceptionHandler 注释(即 except.class.class etc)中定义了异常类型。在这种情况下,联合点方面正在处理建议的异常(此处 ControllerAdvice )方法。

当建议方法中发生例外时,您应该抛出该例外&您的春季建议拦截了例外&将控件传递给点cut,然后匹配异常类型&处理它。

关于 exceptionHandler 的方法签名, doc 说其灵活性&因此,您定义的邮政方法的返回类型并不严格。

ExceptionHandler is pointcut aspects in spring's aspect oriented programming terminologies.

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)

We define type of exception in ExceptionHandler annotation(i.e. Exception.class etc) . Jointpoint aspect in this case is handling exception thrown by advice's (here ControllerAdvice) method.

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.

Reference

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文