SpringBoot2.1.X 全局异常配置返回自定义页面

本文详细介绍了SpringBoot中默认及自定义的异常处理机制,包括针对web浏览器的错误页面响应和接口测试工具的参数响应处理,以及如何通过@ControllerAdvice和@ExceptionHandler注解实现全局异常自定义响应。

在web开发中发生了异常,往往是需要通过一个统一的异常处理来保证客户端能够收到友好的提示。

1、 默认异常机制 :SpringBoot 默认提供了两种机制

        1>针对于web浏览器访问的错误页面响应

        2>针对于 接口测试工具等的参数响应处理

访问:http://localhost:8089/my/ex1 没有找到页面404错误!

 

2、自定义json格式异常响应

通过 @ControllerAdvice/@RestControllerAdvice 和 @ExceptionHandler 注解全局异常自定义响应类

操作步骤:

 1> 异常处理类

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class CustomExtHandler {

    private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);

	
	//捕获全局异常,处理所有不可知的异常
	@ExceptionHandler(value=Exception.class)
	//@ResponseBody
    Object handleException(Exception e,HttpServletRequest request){
		//通过日志跟踪
		LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 
		Map<String, Object> map = new HashMap<>();
	        map.put("code", 100);
	        map.put("msg", e.getMessage());
	        map.put("url", request.getRequestURL());
	        return map;
    }

}

2>Controller类

@RestController
public class ExceptionController {

    //处理全局异常
    @RequestMapping("/my/ex")
    public Object index(){

        int i=2/0;  //发生异常的哦!
        return new Student(11,"john","000");
    }
}

测试:

3、自定义异常处理页面

1> 添加*thymeleaf*依赖

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>

2> resource目录下新建templates|error.html

<h1>发生了异常哦!!!!!</h1>

3> 自定义异常类

/**
 * 功能描述:自定义异常类
 *
 */
public class MyException extends RuntimeException {

    public MyException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private String code;
    private String msg;

...}

4>做错误页面异常处理 返回 ModelAndView

@RestControllerAdvice
public class CustomExtHandler {


	//捕获全局异常,处理所有不可知的异常
	@ExceptionHandler(value=MyException.class)
	Object handleMyException(MyException e,HttpServletRequest request){

		//进行页面跳转
//		ModelAndView modelAndView = new ModelAndView();
//	    modelAndView.setViewName("error.html");
//	    modelAndView.addObject("msg", e.getMessage());
//	    return modelAndView;

		//返回json数据,由前端去判断加载什么页面
		Map<String, Object> map = new HashMap<>();
		map.put("code", e.getCode());
		map.put("msg", e.getMsg());
		map.put("url", request.getRequestURL());
		return map;
	}
	
}

测试:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值