SpringBoot全局异常处理器编写
适用场景: (1)请求比较复杂,其中某些方法抛出了一些异常 (2)参数校验抛出异常 (3)自定义的异常 等等
1. 在请求中抛出异常
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/hello")
public String hello() throws Exception {
if (true) {
throw new Exception("This is my exception");
}
return "hello";
}
}
2. 配置异常处理器
可以把 ResponseBody 和 @ControllerAdvice 合并成为 @RestControllerAdvice
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String, Object> handle(Exception exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 500);
map.put("message", exception.getMessage());
map.put("others", "others");
return map;
}
}
3. 结果
|