在Spring MVC中使用HttpEntity返回错误

时间:2016-02-17 08:54:26

标签: java spring http spring-mvc

我有这段代码:

{
    "feed": {
        "actor": 1986,
        "created_at": 1455690430,
        "foreign_id": "1986",
        "object": {
            "full_name": "Harsewak Singh",
            "login": "harsewak",
            "pic_url": "https:\/\/qbapi.dekhdekh.com\/blobs\/b6e113a29bb34905a14a520917f6da0a00",
            "user": 1986
        },
        "post": {
            "created_at": 1455690430,
            "message": "Hey! How's everyone?",
            "type": "text"
        },
        "to": ["flat:global"],
        "verb": "post"
    },
    "feed_type": "flat",
    "user_id": 1986
}

我想在无法生成报告时返回500错误,但HttpEntity不允许我设置HTTP状态代码。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

您可以使用ResponseEntity(HttpEntity的子代)来设置HTTP状态代码。

public ResponseEntity<byte[]> getReport(){
    WebController.LOGGER.info("Requested report");

    try {
        byte[] reportData= reportService.getReport();
        return new HttpEntity<byte[]>(reportData);
    } catch (ReportGenerationException e) {
        //WHAT DO I RETURN HERE?
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

答案 1 :(得分:0)

我猜你可以创建下一个例外:

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class ReportInternalException extends RuntimeException {
    public ReportInternalException (String message) {
        super(message);
    }
}

把它扔进你的catch区块:

...    
} catch (ReportGenerationException e) {
       throw new ReportInternalException(e.getMessage());
}

答案 2 :(得分:0)

为什么不尝试这个?

return new ResponseEntity<Exception>(e,HttpStatus.INTERNAL_SERVER_ERROR);