/***
* 为什么使用自定义异常?
* 更加精确定位具体异常信息
*
* 继承RuntimeException,实现RuntimeException的所有构造方法,就是一种自定义异常类
*
*/
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = -1169100027771948958L;
public ServiceException() {
super();
// TODO Auto-generated constructor stub
}
public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public ServiceException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public ServiceException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
/**Spring MVC 基于注解方式实现统一异常处理方式
* 规则
* 1)controller内部-->父类-->@ControllerAdvice
* */
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(ServiceException.class)
@ResponseBody
public JsonResult handleServiceException(
RuntimeException e){
System.out.println("handleServiceException");
e.printStackTrace();
//封装错误信息
return new JsonResult(e);
}
@ExceptionHandler(AuthorizationException.class)
@ResponseBody
public JsonResult handleAuthorizationeException(
AuthorizationException e){
System.out.println("handleAuthorizationeException");
e.printStackTrace();
//封装错误信息
return new JsonResult(new ServiceException("没有此权限"));
}
}
/**通过此对象对控制层数据进行封装
* 1)正常数据
* 2)异常数据
* */
public class JsonResult {
private static final int SUCCESS=1;
private static final int ERROR=0;
/**状态码*/
private int state=SUCCESS;
/**状态信息*/
private String message;
/**具体数据*/
private Object data;
public JsonResult() {
message="Action OK";
}
public JsonResult(Object data){
this.data=data;
}
public JsonResult(String message){
this.message=message;
}
public JsonResult(Throwable exp){
this.state=ERROR;
this.message=exp.getMessage();
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}