在做web应用时,请求过程中发生错误是常见的事,而一般界面显示大片白底黑字让人无从下手,对于用户的体验
也不是很好,这时我们可以利用@ControllerAdvice、@ExceptionHandler、@ResponseBody实现全局异常处理,能够帮助
开发者或者客户端迅速定位错误。
步骤:
1.首先我们创建一个JSON返回对象,用来封装{code:消息类型,url:请求地址,data:请求返回的数据,message:错误信息}
package com.wutongshu.springboot.domain; public class ErrorInfo<E> { public static final int OK=0; public static final int ERROR=100; private int code; private String url; private E data; private String message; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public E getData() { return data; } public void setData(E data) { this.data = data; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2.创建一个自定义异常
package com.wutongshu.springboot.exception; public class MyException extends Exception{ public MyException(String message){ super(message); } }
3.在controller中增加测试异常的映射,抛出MyException异常
4.创建一个全局处理异常的类,
@ControllerAdvice 注解定义全局异常处理类
@ExceptionHandler 指定自定义错误处理方法拦截的异常类型
@ResponseBody 指返回JSON类型的数据
package com.wutongshu.springboot; import com.wutongshu.springboot.domain.ErrorInfo; import com.wutongshu.springboot.exception.MyException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; /** * 处理异常类 */ @ControllerAdvice public class GlobalMyExceptionHandler { @ExceptionHandler(value = MyException.class) @ResponseBody public ErrorInfo<String> handlerException(HttpServletRequest request, MyException e){ ErrorInfo<String> errorInfo=new ErrorInfo<>(); errorInfo.setMessage(e.getMessage()); errorInfo.setUrl(request.getRequestURI()); errorInfo.setCode(ErrorInfo.ERROR); errorInfo.setData("错误数据"); return errorInfo; } }
测试:访问http://http://127.0.0.1:8087/test/testException,得到以下内容