【java入门到放弃】@RestControllerAdvice
·
区别
@RestControllerAdvice = @ControllerAdvice + @ResponseBody
| 注解 | 返回格式 |
|---|---|
@ControllerAdvice |
可以返回 页面 / JSON(取决于方法) |
@RestControllerAdvice |
只能返回 JSON(默认) |
作用
@RestControllerAdvice 是 Spring Boot 里用来做全局异常处理 + 全局增强控制器能力的一个注解
语法
//Result里定义返回的code和data
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
return Result.error("系统异常:" + e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public Result handleRuntime(RuntimeException e) {
return Result.error("运行时异常:" + e.getMessage());
}
}
更多推荐



所有评论(0)