Member-only story

Custom exception handling in Spring Boot Application

Sanjay Singh
4 min readJul 5, 2024

--

Custom exception handling in Spring Boot Application

Step 1 — Create Custom Exception Classes

public class ResourceNotFoundException extends RuntimeException {
private final String errorCode;
private final String message;
private final HttpStatus httpStatus;

public ResourceNotFoundException(String message ,String errorCode ,HttpStatus httpStatus) {
super(message ,errorCode ,httpStatus);
}
}

Step 2 — Create Exception Handling Classes

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND, ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}

@ExceptionHandler(BadRequestException.class)
public ResponseEntity<Object> handleBadRequestException(BadRequestException ex, WebRequest request) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}

// Add more exception handling methods as needed
}

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet