Reputation: 6378
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.
Upvotes: 2
Views: 8096
Reputation: 130967
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:
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.
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
Upvotes: 3
Reputation: 1431
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.
Upvotes: 0
Reputation: 2416
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
Upvotes: 0
Reputation: 629
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.
Upvotes: 1