is it correct to throw an exception when resource not found

时光怂恿深爱的人放手 提交于 2021-01-28 08:02:33

问题


Is it fine to throw an exception on the server side when the requested resource was not found?

the client receives a 404 not found. My concern is whether it is fine/wrong to throw an exception on the server side when this happens.


回答1:


It's hard to assume what your are trying to do with the level of details you added to your question.

However, if you handle the exceptions properly, there may be nothing wrong with that approach. Have a look at the approaches used by some frameworks:

JAX-RS

  • You can throw a WebApplicationException, that will be mapped a response. You can define your own subclasses of WebApplicationException or use the existing ones. The NotFoundException, for example, will be mapped to a response with the 404 status code. For more details on the existing exceptions, refer to this answer.

  • You also can create your own ExceptionMapper to map any exception to a desired response.

Spring MVC

  • You can map exceptions to responses by annotating an exception class with @ResponseStatus.

  • It also gives you the possibility to implement a HandlerExceptionResolver or extend one of the existing implementations, such as the AbstractHandlerExceptionResolver.

  • Another approach would be using a ResponseEntityExceptionHandler annotated with @ControllerAdvice and define the handled exceptions by annotating the implemented method with @ExceptionHandler




回答2:


Basically it is not ideal to throw reserved status codes of exception. You should handle this exceptions internally and prepare your own code with meaning full message that client should know the actual problem.




回答3:


From perspective of semantics: Exception should be thrown if condition is such that condition is unrecoverable and devs must be notified about it.

Server cannot resolve auth request in the beginning of a session - this is serious enough situation and exception is appropriate.

User didn't fill out obligatory field and tried sending a form. This problem can be fixed and an exception would be a bad design.




回答4:


I would say add a filter to capture 404 and add custom information about the 404 details.

In case of pure REST implementation, any resource-id missing and malformed URL will return 404. As far as REST contract, both cases are correct to have 404 response. But more details on what type of resource is missing will help the client side consuming it to take appropriate actions.

Related discussion: return-404-when-a-rest-resource-is-not-found



来源:https://stackoverflow.com/questions/43542499/is-it-correct-to-throw-an-exception-when-resource-not-found

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