捕获全局异常或自定义异常
@RestControllerAdvice
标记该类是一个全局异常捕获类
该注解是 @ControllerAdvice + @ResponseBody
@ResponseStatus(HttpStatus.OK)
表示的是返回值的状态码
@ExceptionHandler({UsernameNotFoundException.class})
表示出现UsernameNotFoundException.class异常 会进入到这个方法 执行相应逻辑
Result是统一返回结果类
@RestControllerAdvice
@ResponseStatus(HttpStatus.OK)
public class SecurityExceptionHandler {
private static final String ERROR_CODE="403";
private static final String USERNAMENOTFOUND="账号未注册";
private static final String BADCREDENTIALS="密码错误";
private static final Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);
public SecurityExceptionHandler() {
}
//出现该异常类进入该方法
@ExceptionHandler({UsernameNotFoundException.class})
@ResponseStatus(HttpStatus.OK)
public Result<Object> usernameNotFoundException(Exception e) {
log.error(e.getMessage(), e);
return Result.error(ERROR_CODE,USERNAMENOTFOUND);
}
//捕获自定义异常
@ExceptionHandler({DiaodeyiException.class})
@ResponseStatus(HttpStatus.OK)
public Result<Object> badCredentialsException(Exception e) {
log.error(e.getMessage(), e);
return Result.error(ERROR_CODE,BADCREDENTIALS);
}
}
自定义异常类
package com.hudie.servicebase.exceptionhandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor //生成有参数构造方法
@NoArgsConstructor //生成无参数构造
public class DiaodeyiException extends RuntimeException {
private Integer code;//状态码
private String msg;//异常信息
}