【问题标题】:Displaying the spring boot exceptions in angular application在 Angular 应用程序中显示 Spring Boot 异常
【发布时间】:2019-07-09 16:19:16
【问题描述】:

我正在使用 spring boot 和 angular 开发应用程序,我将如何在 angular 应用程序中显示异常

【问题讨论】:

  • 您应该使用一些 DTO 和 ControllerAdvice 将异常映射到发送到前端的 json 消息。

标签: angular spring spring-boot


【解决方案1】:

我一直这样做,幸运的是这很容易。

为整个应用程序全局执行此操作的最简单/最佳方法是定义 ExceptionHandler 类。这个类是一个带有@ControllerAdvice注解的spring bean,它将全局捕获异常并将它们转换为标准格式。

类似这样的:

@ControllerAdvice
public class JsonExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Object> handleAllOtherErrors(Exception exception) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .contentType(MediaType.APPLICATION_JSON)
                .body(new ErrorResponse(exception.getMessage()));
    }

}

错误响应类将是这样的:

public class ErrorResponse {

    private String message;

    public ErrorResponse(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

附:您可以像这样以不同的方式处理不同的异常,在某些情况下,您可能希望针对特定异常抛出 400 错误请求。您需要做的就是添加另一个方法并更改@ExceptionHandler 注释中的异常。

...

然后从角度来看,您必须检查 HTTP 响应代码,如果响应代码不成功(例如 400、500),您可以阅读响应以查看错误消息。

响应看起来像这样。

{
  "message": "Your exception message"
}

可以通过 response.message 以角度读取(假设是 javascript)

【讨论】:

    【解决方案2】:

    我更喜欢与上面提到的 Rawb 类似的方法:

    首先,控制器:

    @ControllerAdvice
    public class ExceptionController extends ResponseEntityExceptionHandler{
    
      @ExceptionHandler(UsernameNotFoundException.class)   
      public ResponseEntity<?> handleUsernameNotFoundExceptions(UsernameNotFound ex){
        Map<String, String> errors = new HasMap<>();
        errors.put("message", ex.getMessage();
        return new ResponseEntity<>(erros, HttpStatus.CONFLICT);
       }
      }
    

    然后做一个错误响应类(不需要注释):

     public class UsernameNotFoundException extends RuntimeException{
       public UsernameNotFoundException(String username){
        super("Can't find user with this username: " + username);
       }
      }
    

    在 Angular 中,您将获得正确的状态代码(在本例中为 409,表示冲突)和您可以轻松处理的消息:

     { "message": "Can't find user with this username: username" }
    

    Baeldung 有一个伟大的探索:Error Handling for Rest with Spring

    还有角度错误处理: Error Handling with Angular 8

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2018-10-22
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2020-12-20
      相关资源
      最近更新 更多