当前位置: 首页 > 知识库问答 >
问题:

从服务器抛出的CustomError在clientside的HttpErrorResponse中

贺兴昌
2023-03-14

大家好,我对Spring和angular很陌生,我正在构建一个Spring java服务器和一个angular客户机。基本上,我希望客户机能够捕捉从服务器抛出的异常。我定义了一个CustomexEption.java类,并在服务器端有一个CustomRestExceptionHandler.java。现在,我不确定应该在服务器中的哪里抛出异常,以便客户机捕捉。

 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;
    }
}
---
@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个答案

蒋啸
2023-03-14

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

我还尝试了添加在控制器类中的这段代码

@ExceptionHandler(CustomException.class)
public HttpEntity<String> exceptionHandler(CustomException custEx ) {
    return new HttpEntity<String>(custEx.getMessage()) ;
}
 类似资料:
  • 我是新的角度6。我用spring boot开发了一个post服务,当我通过postman测试它时,它工作得很好,但当我用web浏览器测试它时,它给了我这个错误: HttpErrorResponse ;{headers:HttpHeaders,status:500,statusText:“ok”,URL:“http://localhost:8080/api/test/ordermiss”,ok:fa

  • Im编写了一个小的Android应用程序,它应该从npm JSON服务器获取数据。它会抛出一个异常。我确实使用AsyncTask扩展了connection类,并在“DoInBackground”中执行了代码,但它仍然抛出了一个异常。请帮帮我. 代码如下: logcat告诉我们:

  • 试图调试这个简单的NodeJS socketIO服务器。 我在启动时不断收到以下错误消息。我看不出代码有什么问题。 TypeError:侦听器必须是服务器上Namespace.EventEmitter.AddListener(Events.js:130:11)处的TypeError()处的函数。(匿名函数)[如上](/users/foo/bin/node_modules/socket.io/lib

  • Googleapi版本:libs-sources/google-api-services-drive-v2-rev168-1.20.0-sources.jar java版本:“1.7.0_79”java(TM)SE运行时环境(build 1.7.0_79-B15)java HotSpot(TM)64位服务器VM(build 24.79-B02,混合模式) 还将下载的p12文件加载到\jdk1.7.

  • 我想将使用Hazelcast3.12.9作为兑现机制的Spring Boot应用程序升级到Java11和Tomcat9。当我在本地部署时,一切看起来都工作得很好,缓存也成功地工作了。但当应用程序在集群上运行时,我从所有可用的3个节点收到以下错误: Hazelcast自定义程序: 经过几天的调查,我看到了将这些异常抛入并行流中的唯一地方。 奇怪的是,在Java8和Tomcat8中,我没有这个问题。

  • 我在曼宁的练习中练习docker。 技术配方是关于配置jenkins从站,即docker容器。 以下是jenkins_slave 我使用命令构建docker映像 然后,我使用命令将docker映像作为容器运行 然后,我使用下面的docker命令运行jenkins服务器 以下是节点配置详情 - 然后,我收到一条错误消息,说这个代理处于脱机状态,因为Jenkins未能在其上启动代理进程 下面是错误堆栈