package net.kprod.tooling.spring.starter.controller;
@ControllerAdvice
public class RestExceptionHandler {
@Value("${tooling.error.stacktrace.include:false}")
private boolean includeStackTrace;
@ExceptionHandler(value = Exception.class)
public ResponseEntity<ResponseException> handleUnexpectedException(Exception exception) {
HttpServiceException translatedException = new HttpServiceException(
HttpStatus.INTERNAL_SERVER_ERROR,
Msg.format("Unexpected exception [{}:{}]",
exception.getClass().getSimpleName(),
exception.getMessage()),
exception);
return createResponse(translatedException, HttpStatus.INTERNAL_SERVER_ERROR, exception);
}
private ResponseEntity<ResponseException> createResponse(HttpServiceException e, HttpStatus httpStatus, Exception parentException) {
ResponseException responseException = this.processException(e, parentException);
return ResponseEntity.status(httpStatus).body(responseException);
}
private ResponseException processException(HttpServiceException translatedException, Exception parentException) {
ResponseException responseException = new ResponseException();
responseException.setMessage(Msg.format("Exception message [{}] translated to [{}] status [{}]",
parentException.getMessage(),
translatedException.getMessage(),
translatedException.getReason()));
if(includeStackTrace) {
responseException.setStacktrace(getStacktraceAsString(parentException));
} else {
responseException.setStacktrace(STACKTRACE_UNAVAILABLE_MESSAGE);
}
LOG.error(responseException.getMessage());
return responseException;
}
private String getStacktraceAsString(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
}