第十三章、异常实战(SpringBoot2.x)

SpringBoot2.x配置全局异常实战

讲解:服务端异常讲解和SpringBoot配置全局异常实战

        1、默认异常测试  int i = 1/0,不友好
        
        2、异常注解介绍
            @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody
            
            //捕获全局异常,处理所有不可知的异常
            @ExceptionHandler(value=Exception.class)

    -----------------------------------------------------------------------------------

文件结构:

模拟一个controller且出现异常的类:

package net.xdclass.demo.controller;

import java.util.Date;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import net.xdclass.demo.domain.User;

/**
 * 功能描述:异常测试
 * @author wq
 *
 */
@RestController
public class ExceptionController {
	
	@RequestMapping(value = "/api/v1/test_ext")
	public Object index(){
		int i = 1 / 0;
		return new User(11, "asasas", "84411433", new Date());
	}
	
}

再定义一个异常处理器:

package net.xdclass.demo.domain;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class CustomExtHandler {
	
    private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);

	//捕获全局异常,处理所有不可知的异常
	@ExceptionHandler(value=Exception.class)
        public 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;
    }
}

在浏览器访问:http://localhost:8080/api/v1/test_ext

页面显示结果:

------------------------------------------------------------------------------------------------------

SpringBoot2.x配置全局异常返回自定义页面
    简介:使用SpringBoot自定义异常和错误页面跳转实战

    1、返回自定义异常界面,需要引入thymeleaf依赖

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

 2、resource目录下新建templates,并新建error.html

ModelAndView model = new ModelAndView();
model.setViewName("error.html");
return model;

官网:  https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling

测试代码:

自定义一个异常类:

定义一个控制器其中某方法抛出异常

package net.xdclass.demo.controller;

import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.xdclass.demo.domain.MyException;
import net.xdclass.demo.domain.User;

/**
 * 功能描述:异常测试
 * @author wq
 *
 */
@RestController
public class ExceptionController {
	
	/**
	 * 功能描述:模拟全局异常
	 * @return
	 */
	@RequestMapping(value = "/api/v1/test_ext")
	public Object index(){
		int i = 1 / 0;
		return new User(11, "asasas", "84411433", new Date());
	}
	
	/**
	 * 功能描述:模拟自定义异常
	 */
	@RequestMapping(value = "/api/v1/myext")
	public Object myext(){
		throw new MyException("500", "my ext异常");
	}

}

定义处理异常的类:

package net.xdclass.demo.domain;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

@RestControllerAdvice
public class CustomExtHandler {
	
    /**
    * 处理自定义异常
    * @param e
    * @return
    */
    @ExceptionHandler(value=MyException.class)
    public Object handleMyException(MyException e, HttpServletRequest request){
        //进行页面跳转
	ModelAndView model = new ModelAndView();
	model.setViewName("error.html");
        return model;
		
	/*
	//返回JSON数据给前端
	Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        map.put("url", request.getRequestURL());
        return map;
        */
    }
}

当抛出异常时,自定义处理这个异常的时候可以有两种方式,一种是直接跳转到某个页面(例如:error.html)

一种是返回JSON字符串,由前端去判断加载什么页面

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值