springboot 异常捕获和处理
package com.leo23.emp.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BusinessException extends RuntimeException {
private Integer code;
private String message;
}
异常捕获处理
package com.leo23.emp.exception;
import com.leo23.emp.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Slf4j
public class EmpExceptionHandler {
// 系统异常
@ExceptionHandler(Exception.class)
public R systemException(Exception e) {
// 1 记录异常的信息到日志文件
log.error("系统异常", e);
// 2 提示用户
return R.error("系统繁忙,请稍后重试");
}
// 业务异常
@ExceptionHandler(BusinessException.class)
public R businessException(BusinessException e) {
// 1 记录异常的信息到日志文件
log.error("系统异常", e);
// 2 提示用户
return R.error(e.getMessage() + "-->" + e.getCode());
}
}
网友评论