Home > Software design >  What's the best option/alternative to treat exceptions in spring boot?
What's the best option/alternative to treat exceptions in spring boot?

Time:11-23

Right now i'm using this example of exception handling:

//get an object of type curse by id
//in the service file, this findCurseById() method throws a 
//CursaNotFoundException

@GetMapping("/{id}")
public ResponseEntity<curse> getCursaById (@PathVariable("id") Long id) {

        curse c = curseService.findCurseById(id);
        return new ResponseEntity<>(c, HttpStatus.OK);

}

//so if not found, this will return the message of the error

@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(CursaNotFoundException.class)
public String noCursaFound(CursaNotFoundException ex) {
    return ex.getMessage();
}

and that's my exception

public class CursaNotFoundException extends RuntimeException {
    public CursaNotFoundException(String s) {
        super(s);

    }
}

in future I want to use Angular as front-end, so I don't really know how I should treat the exceptions in the back-end. For this example let's say, should I redirect the page to a template.html page in the noCursaFound() method, or should I return something else? A json or something? I couldn't find anything helpful. Thanks

CodePudding user response:

I would suggest keeping the error handling at the REST API level and not redirecting to another HTML page on the server side. Angular client application consumes the API response and redirects to template.html if needed.

Also, it would be better if the backend returns an ApiError when an exception occurs with a message and, optionally, an error code:

public class ApiError {
    private String message;
    private String code;
}

and handle the exceptions in a separate class, ExceptionHandler annotated with @ControllerAdvice:

@ControllerAdvice
public class ExceptionHandler {
    @ExceptionHandler(value = CursaNotFoundException.class)
    public ResponseEntity cursaNotFoundException(CursaNotFoundException cursaNotFoundException) {
        ApiError error = new ApiError();
        error.setMessase(cursaNotFoundException.getMessage());
        error.setCode(cursaNotFoundException.getCode());
        return new ResponseEntity(error, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<> genericException(Exception exception) {
        ApiError error = new ApiError();
        error.setMessase(exception.getMessage());
        error.setCode("GENERIC_ERROR");
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
  • Related