在SimpleController中创建两个会抛出异常的方法
/**
* 使用 try catch 进行异常处理
* @return
*/
@RequestMapping(value = "/test1")
public String test1() {
try {
int i = 1 / 0 ;
} catch (Exception e) {
}
return "Hello World!" ;
}
/**
* 不进行异常处理
* @return
*/
@RequestMapping(value = "/test2")
public String test2() {
int i = 1 / 0 ;
return "Hello World!" ;
}
此时访问http://localhost:8081/test1 时 结果正常 但是访问http://localhost:8081/test2 就会出现异常页面 我们可以创建一个全局异常处理的Controller 对没有处理异常的controller进行处理
/**
* @ControllerAdvice 处理Controller 所有没有被try catch 包裹的注解
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String,Object> handlerException() {
Map<String,Object> map = new HashMap<String, Object>() ;
map.put("code","500") ;
map.put("msg","系统繁忙,稍后再试") ;
return map ;
}
}
对于业务异常 我们也可以进行统一的处理
/**
* 业务异常实体
*/
public class BusinessException extends Exception {
//异常处理编码
private Integer code ;
//异常处理信息
private String msg ;
//具体描述
private String desc ;
public BusinessException() {
super();
}
public BusinessException(String msg) {
this.msg = msg ;
}
public BusinessException(Integer code,String msg,String desc) {
this.code = code ;
this.msg = msg ;
this.desc = desc ;
}
getter / setting 省略
}
在GlobalExceptionHandler中编写处理业务异常的方法
@ExceptionHandler(BusinessException.class)
@ResponseBody
public Map<String,Object> handleBusinessException(BusinessException e) {
Map<String,Object> map = new HashMap<String, Object>() ;
map.put("code",e.getCode()) ;
map.put("msg",e.getMsg()) ;
map.put("desc",e.getDesc()) ;
return map ;
}
在SimpleController中抛出异常
@RequestMapping(value = "/test3")
public String test3() throws BusinessException {
throw new BusinessException(500,"系统出错","系统出错,请稍后访问!") ;
}
完整的全局异常处理类
/**
* @ControllerAdvice 处理Controller 所有没有被try catch 包裹的注解
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/** logger */
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String,Object> handlerException(Exception e) {
Map<String,Object> map = new HashMap<String, Object>() ;
map.put("code","500") ;
map.put("msg","系统出错,请稍后访问!") ;
LOGGER.error("Exception",e);
return map ;
}
@ExceptionHandler(BusinessException.class)
@ResponseBody
public Map<String,Object> handlerBusinessException(BusinessException e) {
Map<String,Object> map = new HashMap<String, Object>() ;
map.put("code",e.getCode()) ;
map.put("msg",e.getMsg()) ;
map.put("desc",e.getDesc()) ;
LOGGER.error("BusinessException",e.getDesc());
return map ;
}
@ExceptionHandler(SQLException.class)
@ResponseBody
public Map<String,Object> handlerSQLException(SQLException e) {
Map<String,Object> map = new HashMap<String, Object>() ;
map.put("code","500") ;
map.put("msg","系统出错,请稍后访问!") ;
LOGGER.error("SQLException",e);
return map ;
}
}