Skip to content

Instantly share code, notes, and snippets.

@WalterInSH
Last active January 1, 2016 07:28
Show Gist options
  • Save WalterInSH/8111425 to your computer and use it in GitHub Desktop.
Save WalterInSH/8111425 to your computer and use it in GitHub Desktop.
Spring mvc central exception handler
import com.walterinsh.datacompass.exception.OperationForbiddenException;
import org.apache.commons.lang.StringUtils;
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;
/**
* User: walter
* Date: 11/20/13
* Time: 4:56 PM
*/
@ControllerAdvice
public class MyExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
logger.error("Got exception",ex);
String message = "Incorrect parameter";
if(StringUtils.isNotBlank(ex.getMessage())){
message = ex.getMessage();
}
return new ResponseEntity(message,HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(OperationForbiddenException.class)
public ResponseEntity<String> handleOperationForbiddenException(OperationForbiddenException ex) {
logger.error("Got exception",ex);
String message = "Operation forbidden!";
if(StringUtils.isNotBlank(ex.getMessage())){
message = ex.getMessage();
}
return new ResponseEntity(message,HttpStatus.FORBIDDEN);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleOtherExceptions(Exception ex) {
logger.error("Got exception",ex);
String message = "Unknown exception";
if(StringUtils.isNotBlank(ex.getMessage())){
message = ex.getMessage();
}
return new ResponseEntity(message,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
<bean id="exceptionHandlerExceptionResolver" class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment