目标:捕获全局异常并对其进行处理
代码:
@ControllerAdvice :表明要作用于哪些Controller类
annotations :表明作用于哪些注解
@ControllerAdvice(annotations = {RestController.class, Controller.class}):表明要作用于加了@RestController和@Controller注解的contoller
@ExceptionHandler:表明要处理哪种异常
package com.ithm.reggie.common;
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})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* 异常处理方法
* @return
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public void exceptionHandler(SQLIntegrityConstraintViolationException ex){
log.error(ex.getMessage());
}
}