SringBoot 异常处理

SringBoot 异常处理

Spring Boot 中默认的错误处理机制

spring boot 应用默认对浏览器请求和Http请求错误处理不同方法

  • spring boot 默认异常处理类
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {}
  • 浏览器访问(请求头包含信息 accept:text/html)
@RequestMapping(produces = "text/html")
	public ModelAndView errorHtml(HttpServletRequest request,
			HttpServletResponse response) {}
  • http请求
@RequestMapping
	@ResponseBody
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {}

自定义异常处理

浏览器访问自定义异常

创建异常页面

  • 在resources下创建resources/error目录
  • 自定义异常页html

返回json数据,自定义异常处理

  1. 自定义异常类型
public class UserNotExistException extends RuntimeException {
    private String id;
    public UserNotExistException(String id) {
    		super("user not exist");
    		this.id = id;
    	}
}	
  1. 定义异常处理类,使用@ControllerAdvice注解专门用来处理controller抛出的异常
@ControllerAdvice
public class ControllerExceptionHandler {
	@ExceptionHandler(UserNotExistException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Map<String, Object> handleUserNotExistException(UserNotExistException ex) {
		Map<String, Object> result = new HashMap<>();
		result.put("id", ex.getId());
		result.put("message", ex.getMessage());
		return result;
	}

}
  • 方法以异常对象作为参数
  • @ExceptionHandler(UserNotExistException.class)指定要处理的异常
  • @ResponseBody返回json串
  • @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)设置返回的状态码
原文地址:https://www.cnblogs.com/fjf3997/p/13023426.html