欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

全集异常处理

发布时间:2025/4/16 编程问答 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 全集异常处理 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

我们的全局异常处理一般都是在controller层捕获异常
核心注解:
(1)@RestControllerAdvice:用于controller层异常捕获
(2)@ResponseStatus(value=,reason=):value属性设置异常的状态码,reaseon是异常的描述.
(3)@ExceptionHandler(value=):value值表示异常的类型.

package com.komorebi.common;import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice;import java.nio.file.AccessDeniedException;@Slf4j @RestControllerAdvice//用于controller层异常捕获 public class GlobalException {@ResponseStatus(HttpStatus.FORBIDDEN)//value值表示异常类别@ExceptionHandler(value = AccessDeniedException.class)public Result handler(AccessDeniedException e) {log.info("security权限不足:----------------{}", e.getMessage());return Result.fail("权限不足");}@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(value = MethodArgumentNotValidException.class)public Result handler(MethodArgumentNotValidException e) {log.info("实体校验异常:----------------{}", e.getMessage());BindingResult bindingResult = e.getBindingResult();ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();return Result.fail(objectError.getDefaultMessage());}@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(value = IllegalArgumentException.class)public Result handler(IllegalArgumentException e) {log.error("Assert异常:----------------{}", e.getMessage());return Result.fail(e.getMessage());}@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(value = RuntimeException.class)public Result handler(RuntimeException e) {log.error("运行时异常:----------------{}", e.getMessage());return Result.fail(e.getMessage());}}

总结

以上是生活随笔为你收集整理的全集异常处理的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。