概述
统一异常处理:统一处理程序中抛出的所有或特定异常.
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; } }
最后
以上就是听话翅膀为你收集整理的Spring Boot 统一异常处理的案例的全部内容,希望文章能够帮你解决Spring Boot 统一异常处理的案例所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复