SpringBoot系列十、异常处理及自定义异常

本文介绍如何在SpringBoot中设置全局异常处理,包括捕获并处理各种异常,以及如何通过自定义异常来增强错误信息。同时,演示了如何通过返回JSON字符串或跳转到特定页面来优雅地处理异常。

一、设置全局异常处理
测试类:

@RestController
public class TestController {
    @GetMapping(value = "/v1/test_exception")
    public Object hello(){
        int i = 1/0;
        return "Hello World!";
    }
}

当启动项目访问http://localhost:8080/v1/test_exception时,页面会报500的错误。
添加一个全局异常处理类,捕获异常

@RestControllerAdvice
public class CustomExtHandler {
    /**
     * 全局异常类处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    Object handlerException(Exception e, HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("code", 100);
        map.put("msg", e.getMessage());
        map.put("url", request.getRequestURL());
        return map;
    }
}

再次访问上面地址时,页面就会显示json字符串,该异常已被捕获,可以进行相应的处理,使页面不会显示500的错误。
二、自定义异常及处理
创建一个自定义的异常类,该类继承RuntimeException

public class MwException extends RuntimeException{
    private String code;
    private String msg;
   //get、set方法
    public MwException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

创建测试方法,直接抛出异常

@GetMapping(value = "/v1/test_mw_exception")
public Object testMwException(){
     throw new MwException("408", "mw exception");
}

1.创建捕获异常的处理方法,返回json字符串

	@ExceptionHandler(value = MwException.class)
    Object handlerException(MwException e, HttpServletRequest request){
        //返回json数据
        Map<String, Object> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        map.put("url", request.getRequestURL());
        return map;
   }

访问http://localhost:8080/v1/test_mw_exception时,会返回json字符串。
2. 创建异常页面,当出现异常时,跳转至该页面
引入模版引擎:

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

在templates下创建error.html页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
error
出异常了!!!
</body>
</html>

更改异常处理方法,使出现异常之后跳转至该异常页面:

@ExceptionHandler(value = MwException.class)
Object handlerException(MwException e, HttpServletRequest request){
     ModelAndView modelAndView = new ModelAndView();
     modelAndView.setViewName("error.html");
     return 	modelAndView;
 }

当再次访问http://localhost:8080/test_mw_exception时,页面直接跳转至error.html。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值