以下是捕获全局异常的demo,请注意红色标记字体 package com.intercepter.myintcedemo.exception; import com.intercepter.myintcedemo.jsonobj.MessageObj; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice//返回异常数据格式为Json public class GloableException { @ExceptionHandler(value = Exception.class)//全局捕获的异常 public MessageObj GloableExceptionHandler(Exception e, HttpServletRequest request) { return new MessageObj(100,"error,please check code!!",request.getRequestURI()); } }
package com.intercepter.myintcedemo.jsonobj; public class MessageObj { private int code; private String msg; private String url; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public MessageObj(int code, String msg, String url) { this.code = code; this.msg = msg; this.url = url; } }
测试接口
package com.intercepter.myintcedemo.controller.api; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestApi { @GetMapping("/extest") public String ExceptionTestHandle(){ int value=1/0; return "this is exception error test!!!"; } }