从服务器抛出的CustomError不在客户端的HttpErrorResponse中返回

时间:2019-01-28 22:28:58

标签: java spring-boot angular7 spring-rest

嗨,我是Spring和Angular的新手,我正在构建一个Spring Java服务器和一个angular客户端。基本上,我希望客户端能够捕获从服务器抛出的异常。我定义了一个CustomExeption.java类,并在服务器端有一个CustomRestExcepotionHandler.java。现在,我不确定应该在服务器中将异常抛出到哪里以供客户端捕获。

我正在学习本教程:https://www.baeldung.com/global-error-handler-in-a-spring-rest-api

现在,它在HttpErrorResponse中向客户端返回500 Internal Server Error错误消息。

我希望它返回我的customexception消息。有人可以帮我看看服务器端代码是否有问题。为什么HttpErrorResponse没有捕获CustomException抛出?谢谢!

 public class ApiError {

    private HttpStatus status;
    private String message;
    private List<String> errors;

    public ApiError(HttpStatus status, String message, List<String> errors) {
        super();
        this.status = status;
        this.message = message;
        this.errors = errors;
    }

    public ApiError(HttpStatus status, String message, String error) {
        super();
        this.status = status;
        this.message = message;
        errors = Arrays.asList(error);
    }

    public HttpStatus getStatus() {
        // TODO Auto-generated method stub
        return status;
    }

    public String getMessage() {
        // TODO Auto-generated method stub
        return message;
    }
}
---

-------------------- ExceptionHandler

@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
            HttpStatus status, WebRequest request) {

         ApiError apiError = 
                  new ApiError(status, ex.getMessage(), ex.getMessage());
                return handleExceptionInternal(
                  ex, apiError, headers, apiError.getStatus(), request);
            }

    protected ResponseEntity<Object> handleResponseStatusException(ResponseStatusException ex,Object body, HttpHeaders headers,
            HttpStatus status, WebRequest request ){
         ApiError apiError = 
                  new ApiError(status, ex.getMessage(), ex.getMessage());
         return handleExceptionInternal(
                  ex, apiError, headers, apiError.getStatus(), request);
            }

}

public ResponseEntity<AtlasJWT> signInUser(String userName, String password) {String userId = "(uid=" + userName + ")";
if (ldapTemplate.authenticate("", userId, password)) {
                log.info("ldapTemplate.authenticate returned true");

                Optional<AtlasUser> optLoggedInUser = userRepository.findByUsername(userName);
                AtlasJWT atlasJwtToken = jwtTokenProvider.createAtlasJwtToken(optLoggedInUser.get());
                if (optLoggedInUser.isPresent()) {
                    log.info("Atlas JWT: {}", atlasJwtToken);
                    return new ResponseEntity<AtlasJWT>(atlasJwtToken, HttpStatus.OK);
                } else {
                    //ApiError error = new ApiError(HttpStatus.BAD_REQUEST,"No such User found in the Atlas Database","No such User found in the Atlas Database");
                    throw new CustomException("No such User found in the Atlas Database",HttpStatus.FORBIDDEN);
                }

            } else {
                //ApiError error = new ApiError(HttpStatus.FORBIDDEN,"Invalid username/password supplied","Invalid username/password supplied");
                throw new CustomException("Invalid username/password supplied", HttpStatus.FORBIDDEN);

            }

    }

我的客户端登录组件如下:

  login(username: string, password: string) {
    console.log('Inside AuthenticationService. Username: ', username);

    // const body = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;

    const body = {
      'username': username,
      'password': password
    };

    const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json',
      })
    };

    console.log('Invoking server authentication for username', username);

    return this.http.post<AtlasJWT>('/auth/api/signin', body, httpOptions).pipe(catchError(this.handleError));
  }

   private handleError(err: HttpErrorResponse) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      errorMessage = err.message;
      // console.log(err);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
      console.log(err);
    }
    console.error(errorMessage);
    return throwError(errorMessage);
  }

1 个答案:

答案 0 :(得分:0)

我觉得这有所帮助。添加了@ResponseBody和@ResponseStatus的注释。

enter image description here

我也尝试将此代码添加到我的控制器类中。两者都正常工作

@ExceptionHandler(CustomException.class)
public HttpEntity<String> exceptionHandler(CustomException custEx ) {
    return new HttpEntity<String>(custEx.getMessage()) ;
}