GlobalExceptionHandler
@ControllerAdvice指定拦截那些类型的控制器
annotations指定只对带有@RestController或@Controller注解的类中的方法进行异常处理。
@ExceptionHandler指定拦截器只拦截哪些错误异常类
package com.example.demo.controller;
import com.example.demo.utils.Result;
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.net.ConnectException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;
/**
* @ControllerAdvice指定拦截那些类型的控制器
* annotations指定只对带有@RestController或@Controller注解的类中的方法进行异常处理。
* @ExceptionHandler指定拦截器只拦截哪些错误异常类
*/
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler({ConnectException.class, SQLIntegrityConstraintViolationException.class, SQLSyntaxErrorException.class})
public Result exceptionHandler(Exception ex){
System.out.println(111111111);
if(ex.getMessage().contains("Duplicate entry")){
String[] split = ex.getMessage().split(" ");
String msg = split[2] + "已存在";
return Result.error();
}
return Result.error();
}
}