1 回答

TA貢獻1772條經驗 獲得超6個贊
你可以直接定義一個錯誤處理器,在service層拋出相關的自定義異常,然后在PersonalExceptionHandler進行相關的處理。
@ControllerAdvice
public class PersonalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
SimpleErrorMessage handleException(EntityNotFoundException exception){
log.debug("Entity Not Found Exception {}",exception.getMessage());
log.trace(exception.getMessage(),exception);
return new SimpleErrorMessage("Entity not found","This resource was not found");
}
@ExceptionHandler({UsernameNotFoundException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
SimpleErrorMessage handleException(UsernameNotFoundException exception){
log.debug("Username not found {}",exception.getLocalizedMessage());
log.trace(exception.getMessage(),exception);
return new SimpleErrorMessage("Unaouthorized"," ");
}
}
添加回答
舉報