spring filter exception handling
- Create a custom exception class:
public class CustomException extends RuntimeException {
// Constructor and custom logic for the exception
}
- Create a custom exception handler:
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(CustomException.class)
public final ResponseEntity<Object> handleCustomException(CustomException ex, WebRequest request) {
// Create a custom error response
ErrorResponse errorResponse = new ErrorResponse("Custom error message", HttpStatus.BAD_REQUEST.value());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
// Handle other exceptions if needed
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
// Create a custom error response for internal exceptions
ErrorResponse errorResponse = new ErrorResponse("Internal error occurred", HttpStatus.INTERNAL_SERVER_ERROR.value());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
- Create a filter for exception handling:
public class ExceptionHandlingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (CustomException ex) {
// Handle custom exception and set response accordingly
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write("Custom error message");
} catch (Exception ex) {
// Handle other exceptions and set response accordingly
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.getWriter().write("Internal error occurred");
}
}
}
- Register the filter in your Spring configuration:
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
@Bean
public FilterRegistrationBean<ExceptionHandlingFilter> exceptionHandlingFilter() {
FilterRegistrationBean<ExceptionHandlingFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new ExceptionHandlingFilter());
registrationBean.addUrlPatterns("/api/*"); // Set the URL patterns to apply the filter
return registrationBean;
}
}
Note: Ensure that you adapt the code according to your project structure and requirements.