您的位置:首页 > 娱乐 > 八卦 > 东莞各镇区疫情最新消息_大连制作网站软件_百度手游排行榜_深圳网站优化平台

东莞各镇区疫情最新消息_大连制作网站软件_百度手游排行榜_深圳网站优化平台

2024/12/23 10:27:52 来源:https://blog.csdn.net/qq_35201802/article/details/143718196  浏览:    关键词:东莞各镇区疫情最新消息_大连制作网站软件_百度手游排行榜_深圳网站优化平台
东莞各镇区疫情最新消息_大连制作网站软件_百度手游排行榜_深圳网站优化平台

定义异常类

package com.shore.my_spring_demo.exception;import com.shore.my_spring_demo.common.enums.ErrorEnums;
import lombok.Data;
import lombok.EqualsAndHashCode;@Data
@EqualsAndHashCode(callSuper = false)
public class UsersException extends RuntimeException {private int code;public UsersException() {super();}public UsersException(String message) {super(message);}public UsersException(String message, Throwable cause) {super(message, cause);}public UsersException(int code, String message, Throwable cause) {super(message, cause);this.code = code;}public UsersException(ErrorEnums errorEnums, Throwable cause) {super(errorEnums.getValue(), cause);this.code = errorEnums.getCode();}public UsersException(ErrorEnums errorEnums) {super(errorEnums.getValue());this.code = errorEnums.getCode();}public UsersException(Throwable cause) {super(cause);}}

定义错误码

package com.shore.my_spring_demo.common.enums;import lombok.AllArgsConstructor;
import lombok.Getter;@Getter
@AllArgsConstructor
public enum ErrorEnums {UN_LOGIN(101, "用户未登录"),USER_NOT_FOUND(102, "用户未找到"),USER_ALREADY_EXIST(103, "用户已存在"),FAIL_VALIDATE(201, "token 校验失败"),FAIL_ENCODE(202, "密码校验失败"),UNKNOWN_ERROR(901, "未知异常"),;private final int code;private final String value;
}

定义全局异常处理 GlobalExceptionHandler

package com.shore.my_spring_demo.web.advice;import com.shore.my_spring_demo.common.enums.ErrorEnums;
import com.shore.my_spring_demo.exception.UsersException;
import com.shore.my_spring_demo.web.domain.common.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(UsersException.class)public ResponseEntity<ApiResponse<Void>> UsersExceptionHandler(UsersException exception) {log.info("errorCode: {}, errorMsg: {}", exception.getCode(), exception.getMessage());return ResponseEntity.badRequest().body(ApiResponse.error(exception.getCode(), exception.getMessage()));}@ExceptionHandler(Exception.class)public ResponseEntity<ApiResponse<Void>> generalExceptionHandler(Exception exception) {log.error("未捕获异常", exception);return ResponseEntity.badRequest().body(ApiResponse.error(ErrorEnums.UNKNOWN_ERROR.getCode(), ErrorEnums.UNKNOWN_ERROR.getValue()));}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com