controller层配置全局配置拦截器

大家好,我是一名在算法之路上不断前进的小小程序猿!体会算法之美,领悟算法的智慧~

希望各位博友走过路过可以给我点个免费的赞,你们的支持是我不断前进的动力!!

加油吧!未来可期!!!

本文介绍的是集中处理异常拦截器

在项目实践中为避免在controller层中多次书写try-catch方法 可以使用全局配置拦截器进行异常处理,具体实现请看下文~

数据库中已经有xiaoyu

1、SQL异常拦截器

为避免在controller中多次书写try-catch方法 使用全局配置拦截器进行异常处理

数据库中已经有xiaoyu

再次添加xiaoyu

程序执行

成功拦截 

代码如下:


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 * @ControllerAdvice(annotations = {RestController.class, Controller.class})
 * RestController.class, Controller.class 添加了这两个注解之后都会被拦截
 * @ResponseBody 把数据封装成json数据
 * @Slf4j 在控制台上写日志
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * SQL SQLIntegrityConstraintViolationException.class 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

//        if(ex.getMessage().contains("Duplicate entry")){
//            String[] split = ex.getMessage().split(" ");
//            String msg = split[2] + "已存在";
//            return R.error(msg);
//        }

        return R.error("未知错误");
    }
}


版权声明:本文为m0_51750419原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。