首页 > 其他分享 >全局异常捕获

全局异常捕获

时间:2024-08-29 09:05:46浏览次数:5  
标签:org 捕获 message ExceptionHandler error import 全局 异常 public

全局异常处理

@RestControllerAdvice

@RestControllerAdvice 是 Spring Framework 4.0 引入的一个注解,它用于定义一个类,该类可以处理多个类型的控制器的异常和横切关注点(cross-cutting concerns),比如日志记录、安全、数据转换等。这个注解是 @Component 的特化,意味着使用 @RestControllerAdvice 注解的类会自动被 Spring 容器管理,并作为候选 Bean 进行依赖注入。

package com.ruoyi.framework.web.exception;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.ResultData;
import com.ruoyi.common.exception.CustomNormalException;
import com.ruoyi.common.exception.DemoModeException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 * 
 * @author ruoyi
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);



    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request)
    {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public ResultData<String > handleException(Exception e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResultData.fail(e.getMessage());
    }

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

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public AjaxResult handleDemoModeException(DemoModeException e)
    {
        return AjaxResult.error("演示模式,不允许操作");
    }
}

@ExceptionHandler

在 Spring MVC 中,使用 @ExceptionHandler 注解的方法可以获取多种类型的参数,这些参数提供了关于异常和请求的上下文信息。以下是一些常用的参数:

  1. 异常参数

    • 直接将捕获的异常类型作为方法参数,例如 ServiceException ex
  2. WebRequest 或 HttpServletRequest

    • WebRequest request:提供了关于当前 HTTP 请求的信息。
    • HttpServletRequest request:提供了标准的 Servlet API 请求信息。
  3. HttpServletResponse

    • HttpServletResponse response:允许你自定义响应头或状态码。
  4. Model

    • Model model:可以向模型中添加属性,这些属性将在视图中被渲染。
  5. HttpServletResponse 或 ResponseEntity

    • HttpServletResponse response:用于自定义响应。
    • ResponseEntity<Object> response:用于构建一个包含状态码和响应体的 HTTP 响应。

  6. BindingResult

    • BindingResult result:如果异常是由数据绑定错误引起的,这个参数将包含绑定的结果。
  7. ValidationUtils

    • @Valid YourObject yourObject@Valid YourObject yourObject, BindingResult result:用于验证表单提交的数据。
  8. LocaleResolver

    • LocaleResolver localeResolver:用于获取当前请求的区域设置。
  9. ThemeResolver

    • ThemeResolver themeResolver:用于处理主题相关的逻辑。
  10. PrincipalAuthentication

    • Principal principalAuthentication authentication:用于获取当前用户的认证信息。

这些参数可以单独使用,也可以组合使用,以满足异常处理的需要。以下是一个示例,展示了如何在 @ExceptionHandler 方法中使用一些常见的参数:

@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public ResponseEntity<Object> handleServiceException(
        ServiceException ex,
        HttpServletRequest request,
        HttpServletResponse response,
        BindingResult result,
        Model model) {

        // 使用参数
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); // 设置状态码
        model.addAttribute("error", ex.getMessage()); // 向模型添加错误信息

        // 构建自定义响应体
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("status", "error");
        responseBody.put("message", ex.getMessage());

        return new ResponseEntity<>(responseBody, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

在这个示例中,handleServiceException 方法捕获了 ServiceException 异常,并使用了请求、响应、数据绑定结果和模型参数来构建一个自定义的响应。这允许异常处理方法根据需要获取请求上下文信息,并自定义响应的内容和状态码。

自定义异常

package com.anze.server.utils.error;

public class ServiceException extends  RuntimeException{

    private int code;
    private String message;


    public ServiceException(int code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }
}

标签:org,捕获,message,ExceptionHandler,error,import,全局,异常,public
From: https://www.cnblogs.com/firsthelloworld/p/18385844

相关文章

  • Java异常详解(全文干货)
    介绍ThrowableThrowable是Java语言中所有错误与异常的超类。Throwable包含两个子类:Error(错误)和Exception(异常),它们通常用于指示发生了异常情况。Throwable包含了其线程创建时线程执行堆栈的快照,它提供了printStackTrace()等接口用于获取堆栈跟踪数据等信息。Error(错......
  • 对数据处理过程中,缺失值和异常值应该怎么处理?
    创作不易,您的关注、点赞、收藏和转发是我坚持下去的动力!大家有技术交流指导、论文及技术文档写作指导、项目开发合作的需求可以私信联系我。在数据处理过程中,缺失值和异常值的处理是非常重要的步骤,它们可能会对模型的性能产生显著影响。以下是一些常用的处理方法:一、缺......
  • openGauss-Anomaly_detection_数据库指标采集_预测与异常监控
    Anomaly-detection:数据库指标采集、预测与异常监控可获得性本特性自openGauss1.1.0版本开始引入。特性简介anomaly_detection是openGauss集成的、可以用于数据库指标采集、预测以及异常监控与诊断的AI工具,是dbmind套间中的一个组件。支持采集的信息包括IO_Read、IO_Write、CPU......
  • c#关于同步 /异常/多线程/事件 事例
    sync同步async异步,要与await成对使用Thread //计算程序执行时间StopWatch sw=StopWatch.Start();转自:https://codeload.github.com/zhaoxueliang86/WinFormsAsyncAwait/zip/refs/heads/BilibiliB站UP主:银色 usingSystem.Diagnostics;usingSystem.Text;na......
  • 网络流量分析与异常检测系统是网络安全领域的重要工具
        网络流量分析与异常检测系统是网络安全领域的重要工具,用于监控网络流量并识别潜在的恶意活动或异常行为这类系统通常结合机器学习、数据挖掘和统计分析技术,以实现高准确性和实时性。在互联网迅速发展的今天,网络安全问题日益突出,网络流量分析与异常检测系统的重要性......
  • 【Shell脚本】根据web访问日志,封禁请求量异常的IP,如IP在半小时后恢复正常,则解除封禁
    #!/bin/bash#####################################################################################根据web访问日志,封禁请求量异常的IP,如IP在半小时后恢复正常,则解除封禁####################################################################################lo......
  • CAS5和CAS6自定义异常提示消息
    CAS5和CAS6自定义异常提示消息使用cas登录时,如果登录错误页面应该提示一下错误消息,cas自带的有一些,不适用的话就需要自定义自己的异常消息提示了。自定义异常提示消息自定义异常消息类例如:验证码异常消息类importjavax.security.auth.login.AccountExpiredException;......
  • vue-router 跳转异常 Error: Navigation cancelled from “/“ to “/home“ with a n
    异常信息:Error:Havigationcancelledfrom"/"to"/home"withanewnavigation ,如下图:原因:    1、这个错误是vue-router内部错误,没有进行catch处理,导致的编程式导航跳转问题,往同一地址跳转时会报错的情况。push和replace都会导致这个情况的发生。   ......
  • vue全局指令按钮权限控制
    方法一:指令.js//注册一个全局自定义指令`v-has-permission`Vue.directive('has-permission',{bind(el,binding,vnode){//获取绑定的权限值constpermission=binding.value;//检查用户是否拥有该权限consthasPermission=checkUserPermissio......
  • 捕获神经网络的精髓:深入探索PyTorch的torch.jit.trace方法
    标题:捕获神经网络的精髓:深入探索PyTorch的torch.jit.trace方法在深度学习领域,模型的部署和优化是至关重要的环节。PyTorch作为最受欢迎的深度学习框架之一,提供了多种工具来帮助开发者优化和部署模型。torch.jit.trace是PyTorch中用于模型追踪的一个重要方法,它能够将一个模......