全局参数、异常处理

简介: 全局参数、异常处理

1、创建全局处理类

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
 * @Description: 全局参数处理
 * @Author: Guo.Yang
 * @Date: 2022/10/10/20:56
 */
@RestControllerAdvice
public class GlobalParametersValidation {
    /**
     * 全局参数处理
     * 控制器注册一个属性编辑器
     * 所谓的属性编辑器可以理解就是帮助我们完成参数绑定。
     * (控制器获取的参数,进行参数的前置处理)
     * @param webDataBinder
     */
    @InitBinder
    public void initData(WebDataBinder webDataBinder){
        Object data = webDataBinder.getTarget();
        System.out.println(data);
    }
    /**
     * 全局异常处理
     */
    @ExceptionHandler({Exception.class})
    public void exceptionHandler(){
        throw new RuntimeException("全局异常处理!");
    }
}

2、创建测试Controller

/**
 * @Description:
 * @Author: Guo.Yang
 * @Date: 2022/10/10/17:48
 */
@RestController
public class HelloController {
    /**
     * 测试controller参数校验
     * @param userDto
     * @return
     */
    @RequestMapping("/test/handler")
    public String testHandler(@Validated @RequestBody UserDto userDto){
        // 测试全局异常处理
//        System.out.println(1/0);
        System.out.println(userDto);
        return "test handler";
    }
    /**
     * 测试get请求,是否会进入 @InitBinder 参数初始化
     * --> 表现是不会的
     * @param id
     * @return
     */
    @GetMapping("/test/{id}")
    public String testHandler(@PathVariable int id){
        System.out.println(id);
        return "test handler";
    }
}

3、示例

package cn.hsa.pss.pw.pcs.manage.exception;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hsa.hsaf.core.framework.web.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
/**
 * @Description: 全局异常处理
 * @Author: Guo.Yang
 * @Date: 2023/08/09/10:19
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 基础异常
     */
    @ExceptionHandler(AppException.class)
    public WrapperResponse<String> baseException(AppException e) {
        return WrapperResponse.error(e.getCode(),e.getMessage(), null);
    }
    /**
     * 业务异常
     */
    @ExceptionHandler(RuntimeException.class)
    public WrapperResponse<String> runtimeException(RuntimeException e) {
        log.error("接口出现异常",e);
        return WrapperResponse.error(-1, e.getMessage(), null);
    }
    @ExceptionHandler(NoHandlerFoundException.class)
    public WrapperResponse handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return WrapperResponse.error(HttpStatus.NOT_FOUND.value(), "路径不存在,请检查路径是否正确", null);
    }
    @ExceptionHandler(AccessDeniedException.class)
    public WrapperResponse handleAuthorizationException(AccessDeniedException e) {
        log.error(e.getMessage());
        return WrapperResponse.error(HttpStatus.FORBIDDEN.value(), "没有权限,请联系管理员授权", null);
    }
    @ExceptionHandler(AccountExpiredException.class)
    public WrapperResponse handleAccountExpiredException(AccountExpiredException e) {
        log.error(e.getMessage(), e);
        return WrapperResponse.fail(e.getMessage(), null);
    }
    @ExceptionHandler(Exception.class)
    public WrapperResponse handleException(Exception e) {
        log.error(e.getMessage(), e);
        return WrapperResponse.fail(e.getMessage(), null);
    }
    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return WrapperResponse.fail(message, null);
    }
}
相关文章
|
3天前
全局异常处理
全局异常处理
27 1
|
3天前
|
程序员
项目中的全局异常是如何处理的
项目中的全局异常处理通常包括对预期异常(程序员手动抛出)和运行时异常的管理。项目已提供`BaseException`作为基础异常类,用于手动抛出异常,并通过`GlobalExceptionHandler`进行全局处理。`
30 4
|
3天前
|
Java
SpringBoot全局异常@RestControllerAdvice全局异常
SpringBoot全局异常@RestControllerAdvice全局异常
12 0
|
10月前
|
运维 Prometheus 监控
java异常 | 处理规范、全局异常、Error处理
java异常 | 处理规范、全局异常、Error处理
|
5月前
|
JSON 前端开发 Java
SpringMVC中异常处理与ControllerAdvice捕捉全局异常
SpringMVC中异常处理与ControllerAdvice捕捉全局异常
60 0
|
8月前
全局统一异常处理
全局统一异常处理
37 0
|
10月前
|
Java
定义全局异常和全局异常处理器
定义全局异常和全局异常处理器
|
JSON 前端开发 数据格式
RestControllerAdvice注解与全局异常处理
从该注解的名字可以看到,这是一个与切面有关的注解,事实上也是如此,我们都知道切面的注解肯定都有个作用范围,切面类的注解只能对其作用范围内的操作,实现切面操作。那RestCntrollerAdvice的作用范围是什么呢?
273 0
|
小程序
为小程序自定义全局方法和全局变量
原生小程序项目开发中,有这个情景,需要将某个方法或者变量,定义到全局变量,来方便全局使用
365 0