Skip to content

Instantly share code, notes, and snippets.

@artemptushkin
Created June 6, 2022 17:03
Show Gist options
  • Save artemptushkin/5f95aac423df69a5d2a440acd658edf3 to your computer and use it in GitHub Desktop.
Save artemptushkin/5f95aac423df69a5d2a440acd658edf3 to your computer and use it in GitHub Desktop.
servlet-exception-handling-filter
@Component
@Profile("servlet")
@RequiredArgsConstructor
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ExceptionHandlingFilter extends OncePerRequestFilter {
private final ServletExceptionHandler exceptionHandler;
/**
* naming this differently than _objectMapper_ you give a chance your code to pass a specific object mapper by the qualifier
* the field name will be considered as the name of the bean
*/
private final ObjectMapper exceptionHandlerObjectMapper;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException {
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
ResponseEntity<ErrorResponse> responseEntity = exceptionHandler.handleException(e);
writeResponseEntity(responseEntity, response);
}
}
private void writeResponseEntity(ResponseEntity<ErrorResponse> responseEntity, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
ErrorResponse error = responseEntity.getBody();
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(responseEntity.getStatusCodeValue());
out.print(exceptionHandlerObjectMapper.writeValueAsString(error));
out.flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment