ErrorResult
作为 responseEntity 的body部分 有errorCode也有errMsg, 总的来说很方便
package com.tanhua.model.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ErrorResult {
private String errCode;
private String errMessage;
public static ErrorResult error() {
return ErrorResult.builder().errCode("999999").errMessage("系统异常稍后再试").build();
}
public static ErrorResult fail() {
return ErrorResult.builder().errCode("000001").errMessage("发送验证码失败").build();
}
public static ErrorResult loginError() {
return ErrorResult.builder().errCode("000002").errMessage("验证码失效").build();
}
public static ErrorResult faceError() {
return ErrorResult.builder().errCode("000003").errMessage("图片非人像,请重新上传!").build();
}
public static ErrorResult mobileError() {
return ErrorResult.builder().errCode("000004").errMessage("手机号已注册").build();
}
public static ErrorResult tokenError() {
return ErrorResult.builder().errCode("000099").errMessage("token无效").build();
}
}
自定义异常
把 errorResult 作为必须填入的元素 这样能方便的把错误信息提取出来
package com.tanhua.server.exception;
import com.easemob.im.server.api.block.group.msg.BlockUserSendMsgToGroup;
import com.tanhua.model.vo.ErrorResult;
import lombok.Data;
/**
* 自定义异常
*/
@Data
public class BusinessException extends RuntimeException{
private ErrorResult errorResult;
public BusinessException(ErrorResult errorResult) {
super(errorResult.getErrMessage());
this.errorResult = errorResult;
}
}
全局异常处理
检测到异常直接响应错误信息
@ControllerAdvice 在类上配
@ExceptionHandler(Exception.class) 在方法上配
package com.tanhua.server.exception;
import com.tanhua.model.vo.ErrorResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.View;
@ControllerAdvice
public class ExceptionAdvice {
private final View error;
public ExceptionAdvice(View error) {
this.error = error;
}
/**
* 全局处理BusinessException.class
* 捕获到异常就直接返回响应
* @param businessException
* @return
*/
@ExceptionHandler(BusinessException.class)
public ResponseEntity handlerException(BusinessException businessException) {
businessException.printStackTrace();//打印堆栈信息
ErrorResult errorResult = businessException.getErrorResult();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
}
@ExceptionHandler(Exception.class)
public ResponseEntity handlerOther(Exception exception) {
exception.printStackTrace();//打印堆栈信息
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResult.error());
}
}