zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JAVA springboot 添加全局异常的处理

JAVASpringBoot异常 处理 添加 全局
2023-06-13 09:15:56 时间

目录

前言

技术方案

具体代码

使用异常代码

运行结果


前言

最近搭建java项目需要进行全局异常的捕获,用于在没有进行异常处理的时候,进行异常报警的处理。

技术方案

使用shiro框架的全局异常处理,前置请求处理adviceRequest;

具体代码

/** *
 * 全局异常处理器
 *
 * @author like.ma
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public AjaxResult handleException(HttpRequestMethodNotSupportedException e)
    {
        System.out.println("不支持' " + e.getMethod() + "'请求");
        LogUtil.WriteErrorLog(null,"不支持' " + e.getMethod() + "'请求");
        return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult notFount(RuntimeException e)
    {
        System.out.println("运行时异常:" + e);
        LogUtil.WriteErrorLog(e,"运行时异常:" + e.getMessage());
        return AjaxResult.error("运行时异常:" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e)
    {
        System.out.println("服务器错误,请联系管理员");
        LogUtil.WriteErrorLog(e,"服务器错误,请联系管理员");
        return AjaxResult.error("服务器错误,请联系管理员");
    }


    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult validatedBindException(BindException e)
    {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }
}

使用异常代码

@ApiOperation("hello 健康检查")
@GetMapping("/hello")
public String getHello(){
    String a = null;
    System.out.println(a.length());
    return  "1";
}

运行结果

​编辑