SpringBoot异常处理机制

前言

SpringBoot对异常有自己的一套处理机制,在实际开发中这个也非常有用,可以增强代码的健壮性,也是一个非常基础的技能,下面就简单说下在SpringBoot工程中怎么使用异常处理!

实现方式

1. 自定义异常页面

我们可以通过在src/main/resources/resources/error路径下定义友好的异常页面,比如定义一个500.html页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>500</title>
</head>
<body>
    系统内部异常
</body>
</html>
我们一般常见的错误有404和500,这是最常见的,在上面定义的目录下面定义404.html或者500.html,当发生对应的错误就会跳到这两个页面,这是最简单的!

2.自定义异常处理

前后端分离的时候,我们想定义一些异常提示,SpringBoot也有方法@ControllerAdvice@RestControllerAdvice
我们手动定义一个UserNotExistException,继承RuntimeException。

public class UserNotExistException extends RuntimeException{

    private static final long serialVersionUID = -1574716826948451793L;

    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;
    }
}

然后定义一个Controller异常处理类ControllerExceptionHandler:

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(UserNotExistException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handleUserNotExistsException(UserNotExistException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", e.getId());
        map.put("message", e.getMessage());
        return map;
    }
}

编写完自定义异常处理逻辑后,我们将UserController中的方法抛出的异常改为UserNotExistException:

@GetMapping("/{id:\\d+}")
public void get(@PathVariable String id) {
    throw new UserNotExistException(id);
}

访问:http://localhost:8080/user/1在这里插入图片描述
是不是很简单?你学会(fei)了吗?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值