zoukankan      html  css  js  c++  java
  • 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)设置返回的状态码
  • 相关阅读:
    netty
    python统计订单走势
    log4j日志写入数据库
    struts 在Action中访问web元素(request,session等)
    struts 简单前台用户名校验
    struts 页面调用Action的指定方法并传递参数
    简单的对象监听器 观察者设计模式
    servlet 简单filter避免中文乱码等
    Struts 第一个Hello页面
    JDBC 使用SimpleJdbcTemplate实现Dao
  • 原文地址:https://www.cnblogs.com/fjf3997/p/13023426.html
Copyright © 2011-2022 走看看