java catch抛出异常,Java抛出异常与catch中的返回响应

I know a lot has been discussed around exception handling, however I need some advice specific to my situation.

I am currently working on a Spring MVC application with Controller->Services->DAO layers. The service classes catch mainly two kinds of exceptions HibernateException and IOException.

HibernateException because service needs to perform rollback if a transaction did not succeed and IOException since it is an unchecked exception and needs to be caught or thrown and I prefer the first option.

Now what would be a better way of handling these further up in the stack :

Should I rethrow these exceptions to the controller and in the

ExceptionHandler of the controller send a HTTP error-code 500

Or in the catch block create the normal JSON response object, setting status=failure and the appropriate error message and return this to the Controller?

解决方案

Exception Handling convensions:

There is a saying that, best way of handling Exception is not to handle it!

For Spring's convention of controllerservicedao layers, Exception handling mechanism is known as Bubble up. Any exception occurs in the dao or service layer, you should pop it up to the controller layer (by adding throws XXXException in dao and service layer's method signature, is the most common way). Only controller layer should handle Exceptions.

Here is a nice tutorial of how you can handle exceptions for REST with spring.

Send HTTP Status code 500 or JSON object with status:

Sounds like you are writing API with Spring MVC. Look, when you are writing API's you should follow the proper conventions. It is Globally accepted that for internal server errors you send HTTP response with code 500, that means internal server errors.

There are number of causes for what you should not send JSON response in this case. One of the main cause is the implicit assumption of your API client. That is HTTP response with code 200 with a JSON object means every thing went normal. And thus the client side business logic may reflect that assumption which is wrong eventually.

Here you can see some API error code conventions for some well-known organizations:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值