全局异常构建
package com.lingyang.system.util.exception;
import lombok.Getter;
/**
* @author **文
* @Description:
* @createDate 2024/8/8 15:20
**/
@Getter
public class TokenErrotException extends RuntimeException{
private final String errorMessage;
public TokenErrotException(String errorMessage) {
this.errorMessage = errorMessage;
}
}
异常捕获与返回
package com.lingyang.system.util.exception;
import com.lingyang.system.util.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import org.springframework.core.Constants;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
/**
* @author 黑锦鲤
* @Description:
* @createDate 2024/7/19 11:36
**/
@ResponseBody
@ControllerAdvice
public class MyGlobalExceptionHandler {
@ExceptionHandler(value = TokenErrotException.class)
public Result<String> handleException(TokenErrotException e) {
return Result.tokenError(e.getMessage());
}
}
返回结果