1、Spring boot对全局异常处理的支持
-
SpringBoot提供了两个注解用于拦截异常
-
1、@ControllerAdvice:标注该类为全局异常处理类,默认拦截所有被触发的异常
-
2、@ExceptionHandler:标注方法,用于处理特定异常
-
注意:@ControllerAdvice针对@Controller注解产生的异常,异常处理需要返回视图,又针对@RestController设计了@RestControllerAdvice,可以直接返回数据。 如下代码可以看出二者关系。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {
//一系列属性
}
2、定义一个接口返回数据类型,正好用来异常处理的返回
package com.ld.exception.common;
public class ResponseResult {
private String msg;
private Integer code;
private boolean success;
private Object data;
public ResponseResult() {
super();
}
public ResponseResult(String msg, Integer code, boolean success, Object data) {
super();
this.msg = msg;
this.code = code;
this.success = success;
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static ResponseResult ok() {
return new ResponseResult ("ok", 200, true, null);
}
public static ResponseResult ok(Object data) {
return new ResponseResult ("ok", 200, true, data);
}
public static ResponseResult fail() {
return new ResponseResult ("服务器忙,请稍后再试", 500, false, null);
}
public static ResponseResult fail(String msg) {
return new ResponseResult (msg, 500, false, null);
}
public static ResponseResult fail(String msg,Integer code) {
return new ResponseResult (msg, code, false, null);
}
}
3、定义一个异常处理Handler
package com.ld.exception.handler;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;
import com.ld.exception.common.ResponseResult;
@RestControllerAdvice
public class GlobalExceptionHandler {
/** 通过handlerMethod、webRequest,可以获取更多的上下文信息,如请求信息、控制器方法参数等
* @param e
* @param handlerMethod
* @param webRequest
* @return
*/
@ExceptionHandler({Exception.class})
public ResponseResult exceptionHandler(Exception e, HandlerMethod handlerMethod,NativeWebRequest webRequest){
return ResponseResult.fail(e.getMessage());
}
}
4、测试体验一下
package com.ld.exception.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ld.exception.common.ResponseResult;
@RestController
public class ExceptionController {
@GetMapping("/hello")
public ResponseResult world() {
Integer i=null;
if(i==1) {
}
return ResponseResult.ok();
}
}