0
votes

I am trying to develop an application with spring boot. I am stuck on managing exception/error for the application. So far I have service layer and controller and I have created service class specific exceptions. for.eg. AnimalService exception class is AnimalServiceException. Services throw respective ABCServiceException. I am stuck on how to handle exceptions/errors in the controller if there are exceptions there? Specifically for ill-formatted input to api method call. I am reading inputs in Controller. Should I include that in service?

All the service exceptions are returning HTTP code as 500 internal application errors. I want to capture those exceptions somehow but donno how.

What qualifies as error vs exception in spring boot?

2

2 Answers

0
votes
0
votes

We can create customized exception: @ResponseStatus(HttpStatus.NOT_FOUND) public class StudentNotFoundException extends RuntimeException {}

Exception handler in Spring:

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends 
ResponseEntityExceptionHandler {
@ExceptionHandler(StudentNotFoundException.class)
public final ResponseEntity<ErrorDetails> 
handleUserNotFoundException(StudentNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),
    request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}


public class ErrorDetails {
private Date timestamp;
private String message;
private String details;

public ErrorDetails(Date timestamp, String message, String details) {
  super();
 this.timestamp = timestamp;
 this.message = message;
 this.details = details;
}