zoukankan      html  css  js  c++  java
  • 04 异常处理

    异常处理

    有时候不可避免服务器报错的情况,如果不配置异常处理机制,就会默认返回tomcat或者nginx的5XX页面,对普通用户来说,不太友好,用户也不懂什么情况。这时候需要我们程序员设计返回一个友好简单的格式给前端。

    处理办法如下:通过使用@ControllerAdvice来进行统一异常处理,@ExceptionHandler(value = RuntimeException.class)来指定捕获的Exception各个类型异常 ,这个异常的处理,是全局的,所有类似的异常,都会跑到这个地方处理。

    • com.gychen.common.exception.GlobalExceptionHandler

    步骤二、定义全局异常处理,@ControllerAdvice表示定义全局控制器异常处理,@ExceptionHandler表示针对性异常处理,可对每种异常针对性处理。

    /**
     * 全局异常处理
     */
    @Slf4j
    @RestControllerAdvice
    public class GlobalExceptionHandler {
    
        @ResponseStatus(HttpStatus.UNAUTHORIZED)
        @ExceptionHandler(value = ShiroException.class)
        public Result handler(ShiroException e) {
            log.error("运行时异常:----------------{}", e);
            return Result.fail("401", e.getMessage(), null);
        }
    
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ExceptionHandler(value = MethodArgumentNotValidException.class)
        public Result handler(MethodArgumentNotValidException e) {
            log.error("实体校验异常:----------------{}", e);
            BindingResult bindingResult = e.getBindingResult();
            ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
    
            return Result.fail(objectError.getDefaultMessage());
        }
    
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ExceptionHandler(value = IllegalArgumentException.class)
        public Result handler(IllegalArgumentException e) {
            log.error("Assert异常:----------------{}", e);
            return Result.fail(e.getMessage());
        }
    
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ExceptionHandler(value = RuntimeException.class)
        public Result handler(RuntimeException e) {
            log.error("运行时异常:----------------{}", e);
            return Result.fail(e.getMessage());
        }
    
    }
    
    
    

    上面我们捕捉了几个异常:

    • ShiroException:shiro抛出的异常,比如没有权限,用户登录异常
    • IllegalArgumentException:处理Assert的异常
    • MethodArgumentNotValidException:处理实体校验的异常
    • RuntimeException:捕捉其他异常

    最后在Controller层的页面方法上添加上@RequireAuthentication,该页面就需要登录验证才能访问

  • 相关阅读:
    select * from a,b探讨
    使用python脚本从数据库导出数据到excel
    git入门
    登录远程服务器脚本
    Ubuntu下python开发环境搭建
    asyncio并发编程
    深入理解python协程
    单例模式的几种实现方式
    MySQL统计百分比结果
    Java查询MySQL数据库指定数据库中所有表名、字段名、字段类型、字段长度、字段描述
  • 原文地址:https://www.cnblogs.com/nuister/p/13495368.html
Copyright © 2011-2022 走看看