Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of throwing exception by Spring controller function

I have come across few Spring contoller's function, which are throwing IOException.

@RequestMapping(method = ***)
@ResponseBody
public List<Offering> getOfferingDetailsList(HttpServletResponse response, @PathVariable("productIds") String productIdString, HttpServletRequest request) throws IOException

I doubt about use of such exception throwing, when no one above is catching and handling it.

Is it fine to set response status like "response.setStatus(HttpStatus.SC_NOT_FOUND)" in place of throwing such exception ?
What is the standard way of handling exception in controller ?

like image 440
user811602 Avatar asked Dec 31 '25 02:12

user811602


2 Answers

it is always good to have common exception handling functionality , so that we can make our controller code free from exception handling , by externalize to common exception handling functionality, i have come across this interesting topic for this purpose

http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

and also use a global exception handler that will do that for all the exceptions of all the controller methods. That will centralize the exception handling, prevent massive code duplication, and avoid cluttering your controller methods.

Look at the @ControllerAdvice and @ExceptionHandler annotations.

like image 72
pappu_kutty Avatar answered Jan 02 '26 17:01

pappu_kutty


A fairly standard way of handling exceptions in Spring Controllers is to use @ExceptionHandler.

Check out this post for more details

like image 30
geoand Avatar answered Jan 02 '26 15:01

geoand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!