全局异常

2022/7/21 6:25:50

本文主要是介绍全局异常,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package com.itheima.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理返回数据
@RestControllerAdvice("com.itheima.controller")
public class GlobalExceptionHandler {
    @ExceptionHandler
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();

        if (message.contains("Duplicate entry")){
            //切割第三个字母是输入的名字
            String[] s = message.split(" ");
            return R.error(s[2]+"已存在");

        }
        return R.error("未知错误");
    }
    @ExceptionHandler
    public R<String> customExpectionHandler(CustomExpection ex){
       return R.error(ex.getMessage());
    }
}


这篇关于全局异常的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程