RestControllerAdvice和ControllerAdvice是全局接口异常处理的类,当发生异常没有捕获时,便会触发这个异常,一般用法如下
package test.controller.advice.advice;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
public String exception(Exception e) {
return "这是一个全局处理异常 " + JSONObject.toJSONString(e);
}
@ExceptionHandler(IndexOutOfBoundsException.class)
public String arrayOutOfRangeException(Exception e) {
LOGGER.error("数组越界 ",e);
return "数组越界 " + e.getMessage();
}
}
再写一个controller
package test.controller.advice.controller;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("test/advice")
public class TestController {
private final static Logger LOGGER = LoggerFactory.getLogger(TestController.class);
@GetMapping("exception")
public void exceptionController(){
try{
int a = 1/0;
}catch (Exception e){
e.printStackTrace();
LOGGER.error(e.getMessage());
}
}
@GetMapping("arrayOutOfRange")
public void arrayOutOfRangeExceptionController(){
List<String> list = Lists.newArrayList("a","b","v");
System.out.println(list);
System.out.println(list.get(4));
}
}
@ExceptionHandler中定义具体异常,如定义了具体的异常,就不会走Exception这个父类异常了。
这种方式会捕获了异常对外却不知道,因为我们在全局异常那边没有把异常信息打印出来,所以需要再加上日志,更改如下:
package test.controller.advice.advice;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
public String exception(Exception e) {
// 打印出错误日志
LOGGER.error(e.getMessage(), e);
return "这是一个全局处理异常 " + e.getMessage();
}
@ExceptionHandler(IndexOutOfBoundsException.class)
public String arrayOutOfRangeException(Exception e) {
LOGGER.error(e.getMessage(), e);
return "数组越界 " + e.getMessage();
}
}
这样就能打印出日志,并且配置到日志文件里了。