全局异常

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());
}
}
posted @ 2022-07-20 23:21  pengkangwzw  阅读(25)  评论(0)    收藏  举报