Spring Boot Web專案統一處理Controller拋出的例外錯誤可用@ControllerAdvice或@RestControllerAdvice,兩者區別如下。
@RestControllerAdvice其實只是@ControllerAdvice加上@ResponseBody,也就是@RestControllerAdvice類方法回傳的內容會包在response body中。
從@RestControllerAdvice的原始碼可清楚看到以上關係。
@RestControllerAdvice
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {
...
}
兩者的關係就像@RestController與@Controller。
若Controller都是REST API的話就用@RestControllerAdvice比較方便。
沒有留言:
張貼留言