在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。参考:@ControllerAdvice 文档
创建全局统一处理异常类 GlobalExceptionController
package cn.fllday.controller;
import cn.fllday.common.response.ResponseData;
import cn.fllday.exception.ParamException;
import cn.fllday.exception.UnLoginException;
import org.apache.shiro.authz.AuthorizationException;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.sql.SQLIntegrityConstraintViolationException;
/**
* 永无八阿哥
*
* @Author:gssznb
* @Date:Created 2019/1/148:37
* @Description: 这是一个描述,但是我可能不会写
* @Modified By:
*/
@ControllerAdvice
public class GlobalExceptionController {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionController.class);
@ResponseBody
@ExceptionHandler(value = Exception.class)
public ResponseData paramErrorHandler(Exception e){
e.printStackTrace(System.out);
log.info(e.getMessage());
return ResponseData.forbidden().putDataValue("msg",e.getMessage());
}
}
上面代码的意思就是。如果我访问的Controller发生了我通过@ExceptionHandler
指定得异常 Exception
。就会不执行Controller的逻辑。来执行我这段代码。相当于把try{}catch(){}
提取了出来。使代码更加简洁。
可以故意制造一个异常。来测试一下
@Controller
@RequestMapping(value="test")
public class Test{
@GetMapping(value="ceshi")
public String haha(){
1/0;
return "success";
}
}