Last active
January 1, 2016 07:28
-
-
Save WalterInSH/8111425 to your computer and use it in GitHub Desktop.
Spring mvc central exception handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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