Spring Boot 统一异常处理的案例
统一异常处理:统一处理程序中抛出的所有或特定异常.
1.返回页面的数据类型为:Json格式
package com.example.demo.error;
/**
* Create by szw on 2017/11/29 16:31
*/
public class ErrorInfo<T> {
public static final Integer OK = 0;
public static final Integer ERROR = 100;
private Integer code;
private String message;
private T data;
public static Integer getOK() {
return OK;
}
public static Integer getERROR() {
return ERROR;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
2.自定义异常类
package com.example.demo.exception;
import sun.plugin2.message.Message;
/**
* Create by szw on 2017/11/29 16:32
*/
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
3.统一异常处理
package com.example.demo.exception;
/**
* Create by szw on 2017/11/29 15:59
*/
import com.example.demo.error.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* 统一异常处理
*/
@ControllerAdvice
class GlobalExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler(value = MyException.class)
@ResponseBody
public ErrorInfo defaultErrorHandler(HttpServletRequest req, MyException e) throws Exception {
ErrorInfo<String> stringErrorInfo = new ErrorInfo<>();
stringErrorInfo.setMessage(e.getMessage());
stringErrorInfo.setCode(ErrorInfo.ERROR);
stringErrorInfo.setData("some date");
return stringErrorInfo;
}
}
还没有评论,来说两句吧...