WebApplicationException vs Response

冷暖自知 提交于 2019-12-31 08:45:32

问题


Among all the possibilities to return a response to the client in a REST service, I've seen two possibilities that look equivalent: throwing a WebApplicationException (possibly using a Response instance) or returning a Response instance.

Why to use one possibility over the other since the result is the same? Is this related to the REST framework used that may be configured to react differently between exceptions and regular responses?


回答1:


Why to use one possibility over the other since the result is the same?

Maybe because as a (Java) programmer you are accustomed with throwing exceptions when particular rules of the application are broken? Convert some string to a number and you might get a NumberFormatException, use a wrong index in an array and you get an ArrayIndexOutOfBoundsException, acces something you are not allowed to and get a SecurityException etc. You are used to throwing exceptions when the "regular response" can't be created (be it from wrong input or some processing error).

When you can't return the regular response, you must return an error response to the client. You can do that with either throwing the exception or building the response by hand. It's the same thing for your client, but it's not the same thing for your server side code.

Throwing the exception makes your code cleaner, easier to reason about and thus easier to understand. The idea is to subclass the WebApplicationException and create your own meaningful exceptions out of it (e.g ProductNotFoundException extends WebApplicationException { ... }, AccessDeniedException extends WebApplicationException { ... } or reusing exceptions with an exception mapper).

It's then cleaner to throw new ProductNotFoundException() or throw new AccessDeniedException() and let the framework handle it instead of building a Response every time and later follow the details used to build it to figure out what's happening in that section of code.



来源:https://stackoverflow.com/questions/13359396/webapplicationexception-vs-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!