Skip to content

Instantly share code, notes, and snippets.

@alexcheng1982
Created March 8, 2018 19:01
Show Gist options
  • Save alexcheng1982/9fb570cac5a099e0d824ce71cd9fac2b to your computer and use it in GitHub Desktop.
Save alexcheng1982/9fb570cac5a099e0d824ce71cd9fac2b to your computer and use it in GitHub Desktop.
Spring MVC exception handler
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
@ControllerAdvice
@RestController
public class DefaultExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionHandler.class);
@ExceptionHandler(Exception.class)
public final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) {
LOGGER.warn("Internal error", ex);
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment