Skip to content

Instantly share code, notes, and snippets.

@MrMjauh
Last active June 28, 2019 11:25
Show Gist options
  • Save MrMjauh/a0e9ca769b3766a9a4da927858293ab5 to your computer and use it in GitHub Desktop.
Save MrMjauh/a0e9ca769b3766a9a4da927858293ab5 to your computer and use it in GitHub Desktop.
Excpetion Handling
package com.codecamos.timetracking.config;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private Environment env;
private static final Logger logger = LogManager.getLogger(RestResponseEntityExceptionHandler.class);
public static final HttpStatus DEFAULT_STATUS_CODE = HttpStatus.BAD_REQUEST;
@Autowired
public RestResponseEntityExceptionHandler(Environment env) {
this.env = env;
}
@ExceptionHandler(Exception.class)
protected ResponseEntity<Object> handleConflict(
final Exception ex, final WebRequest request) {
HttpStatus status = DEFAULT_STATUS_CODE;
ApiError apiError;
if (ex == null) {
apiError = Resource.GENERIC_ERROR;
}
else if (ex instanceof BaseException) {
BaseException baseException = (BaseException) ex;
apiError = new ApiError();
apiError.setCode(baseException.getCode());
apiError.setMessage(baseException.getMessage());
if (ex.getClass().isAnnotationPresent(ResponseStatus.class)) {
ResponseStatus responseStatusAnnotation = ex.getClass().getAnnotation(ResponseStatus.class);
status = responseStatusAnnotation.code();
}
}
else {
apiError = Resource.GENERIC_ERROR;
}
logger.error(ex);
// Make sure exceptions are only sent in dev or stage
// Depending on your security, maybe even go as far to future toggle this
if (Resource.isInDevOrStage(this.env.getActiveProfiles())) {
apiError.setException(ex);
}
return handleExceptionInternal(ex, apiError,
new HttpHeaders(), status, request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment