Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Exception(Error) Handling for RESTful Services

I have the following RESTful Services method :

@PostMapping("/ajouterNewField")
public String ajouterField(@Valid @ModelAttribute("field") Fields field, Model model) throws IOException {  

    fieldDao.save(field);
    // SOME CODE 
    return displayListeChamps( model);
}

The method is working fine and my question is how to handle any error (database not connected ...) or every issue that can happen durring the execution of this RESTful Services method.

like image 217
Yagami Light Avatar asked Jan 29 '26 16:01

Yagami Light


1 Answers

You can use @ControllerAdvice Refer to the code below

@ControllerAdvice
public String NyExceptionHandlerAdvice {
    private final Logger logger = ...;

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({MyRunTimeException.class})
    public void handleMyRunTimeException(Exception e) {
        logger.error("Exception : ", e);
    }
    return MY_ERROR_STRING;
}

Best Practice is: You can have your code throw RunTimeExceptions and handle all of them together or separately in handler methods similar to handleMyRunTimeException above.

You can decide what status code your request should return upon exception.

like image 58
Amit Phaltankar Avatar answered Feb 01 '26 07:02

Amit Phaltankar



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!