【问题标题】:Spring RestController returning ResponseEntity<byte[]> in case of errorsSpring RestController 在出现错误时返回 ResponseEntity<byte[]>
【发布时间】:2019-09-08 16:46:55
【问题描述】:

我在 Spring Boot 服务中有一个休息控制器,如下所示:

Public ResponseEntity getDocContent(String id)

这个控制器动作产生 MediaType.Octet_Stream

我想知道当我真的没有字节数组内容而是带有错误消息的字符串时,如果非 Http OK 响应返回什么。我不想在错误情况下生成八位字节流,而是生成错误 JSon

我可以让服务同时生成八位字节流和应用程序/json,但我的困惑是字节数组的返回类型,以防万一出现错误,在这种情况下我想生成 Json 而不是字节数组

请告诉我如何解决这个问题

【问题讨论】:

  • 你试过抛出异常并在前端处理吗?
  • 我仍然需要返回一个错误HttpStatus代码以防出错

标签: spring spring-boot


【解决方案1】:

RestContoller中添加controllerAdvice处理抛出的异常。

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler{


    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.CONFLICT) //Just an example code
    public ResponseEntity<GeneralMessage> handleGacaException(MyException ex) {
        LOGGER.error(ex.getMessage());
        GeneralMessage errorMessage = new GeneralMessage(ex.getErrorCode().toString(), ex.getErrorMessage());

        return ResponseEntity.status(HttpStatus.CONFLICT).body(errorMessage);
    }


}

而不是在 RestController 上抛出 MyException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2017-04-07
    相关资源
    最近更新 更多