Exception Handling integrated by spring mvc and mybatis, mvcmybatis
1. custom exception information class receives exception information through Constructor
Public class CustomException extends Exception {
// Exception information
Private String message;
Public CustomException (String message ){
Super (message );
This. message = message;
}
Public String getMessage (){
Return message;
}
Public void setMessage (String message ){
This. message = message;
}
}
2. implement the HandlerExceptionResolver interface to implement exception handling process: first, parse the exception and then determine whether it is a custom system exception. If yes, an exception is thrown directly, if it is not a custom exception, you can directly construct a custom exception type (the message is "Unknown error, please contact the administrator! ")
// If it is not a custom hunger exception, most of them are running exceptions. Try to solve this problem during testing.
Public class CustomExceptionResolver implements HandlerExceptionResolver {
@ Override
Public ModelAndView resolveException (HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex ){
CustomException customException = null;
If (ex instanceof CustomException ){
CustomException = (CustomException) ex;
} Else {
CustomException = new CustomException ("Unknown error, please contact the administrator! ");
}
// Get error information
String message = customException. getMessage ();
System. out. println ("exception message:" + message );
// Create a ModelAndView object
ModelAndView modelAndView = new ModelAndView ();
// Fill in the error information in the request domain
ModelAndView. addObject ("message", message );
// Input to the page
ModelAndView. setViewName ("error ");
Return modelAndView;
}
}
3. Configure the class as the CustomExceptionResolver path in the xml file of spring.
<! -- Exception Processor -->
<Bean class = "com. menglin. ssm. exception. CustomExceptionResolver"> </bean>
4. Start the test (requirement: if the information does not exist during the query, an exception is thrown)
/**
* Query by id
*/
@ Override
Public ItemsCustom findItemsCustomById (Integer id) throws Exception {
ItemsCustom itemsCustom = null;
Items items = itemsMapper. selectByPrimaryKey (id );
If (items = null ){
Throw new CustomException ("the product information does not exist! ");
} Else {
ItemsCustom = new ItemsCustom ();
BeanUtils. copyProperties (items, itemsCustom );
}
Return itemsCustom;
}
5. display of error messages