springboot全局异常捕获

springboot全局异常捕获

有时候在操作数据库的时候会出现异常,处理异常
创建一个全局异常处理类
如:

package com.dahai.springboot;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

// 全局异常捕获
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody   // 如果返回String或json要加此注解如果返回界面就不加
    public String defaultExceptionHandler(HttpServletRequest req, Exception e) {

        System.out.println("有异常啦");
        // 返回String
        return "对不起服务器繁忙";

        // 返回View 创建ModelAndView  mv = new ModelAndView("error")
    }
}

我们可以自定义异常,比如在请求接口时参数缺失就可以采用抛异常的方式退出,然后在全局异常处理处获取到异常信息返回给客户端

    @GetMapping("/findName")
    public Demo findDemoByName(String name) throws Exception {
        if (name==null || name.length()==0) {
            throw new Exception("参数缺失或为空");
        }
        return demoService.likeName(name);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody   // 如果返回String或json要加此注解如果返回界面就不加
    public String defaultExceptionHandler(HttpServletRequest req, Exception e) {

        System.out.println("有异常啦"+e.getMessage());
        // 返回String
        return e.getMessage();

        // 返回View 创建ModelAndView  mv = new ModelAndView("error")
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值