一,应用场景
在三层架构中,当一层出现异常时,如果不处理异常,会一层已一层向上抛,最后抛给框架,但是框架返回的值不符合开发规范,因此我们需要定义全局异常处理器。
二,示例代码
package com.example.tiaswebmanagement.execption;
import com.example.tiaswebmanagement.pojo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice//@RestControllerAdvice=@ControllerAdvice+@ResponseBody定义了一个全局异常处理器
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)//捕获所有异常
public Result ex(Exception ex ){
ex.printStackTrace();
return Result.error("操作失败,请联系管理员");
}
}