zoukankan      html  css  js  c++  java
  • SpringBoot 默认400,500 异常处理,自定义异常处理

    在resources 目录下 创建 resources/error 即可,浏览器访问会跳转至定义的页面中

    ajax请求自定义异常处理 消息

    UserNotExistException .java
    package com.imooc.exception;
    public class UserNotExistException extends RuntimeException {
    	private static final long serialVersionUID = -6112780192479692859L;
    	
    	private String id;
    	
    	public UserNotExistException(String id) {
    		super("user not exist");
    		this.id = id;
    	}
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    }
    

      ControllerExceptionHandler .java

    package com.imooc.web.controller;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    import com.imooc.exception.UserNotExistException;
    
    /**
     * 自定义异常处理响应内容
     */
    @ControllerAdvice
    public class ControllerExceptionHandler {
    	// 抛出 UserNotExistException 异常都会被拦截
    	@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;
    	}
    
    }
    

      

    业务逻辑中抛出异常

  • 相关阅读:
    HDU1698(线段树入门题)
    POJ2528(离散化+线段树区间更新)
    POJ3630(Trie树)
    HDU1251(字典树)
    HDU1247(经典字典树)
    POJ2513(字典树+图的连通性判断)
    POJ1363
    UVa11624(逃离火焰问题)
    HDOJ1495(倒水BFS)
    poj3414Pots(倒水BFS)
  • 原文地址:https://www.cnblogs.com/412013cl/p/14050490.html
Copyright © 2011-2022 走看看