简体   繁体   中英

How to handle Exceptions in Rest API whit Spring boot

I need to handle the exceptions in My rest API. I have a layered architecture, composed by Entities, DAOs, Services and controllers. In my services I have the model Exceptions, and I need to know the best way to translate these exceptions to send responses in HTTP. I read about Exception handler and Controller advice but I'm not sure how is the best form to do this. Anyone can iluminate me? Thanks

I would go with @ControllerAdvice for most of the exceptions, for instance, validation error, system errors etc. On the other hand, you could use error handlers for specific cases in your controllers.

This way you have generalized error handler with the possibility to overwrite the default error handling.

One way is by the use of spring ExceptionHandler (there are several variants possible depending on spring version).

Some good documentation here

最好的方法是创建自己的自定义异常类,并且不处理dao&services中的任何异常,而不仅仅是从那里抛出自定义异常,然后处理控制器中的所有异常并响应,这意味着从控制器向客户端发送完整消息。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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