Spring MVC:异常后还有200 OK响应

时间:2014-04-24 15:00:59

标签: spring-mvc

我有控制器

@RequestMapping(value="fetchprofilepics/{profileId}/{column}/{random}",method=RequestMethod.GET)
public void fetchProfilePhoto(HttpServletResponse response, @PathVariable String profileId, @PathVariable String column, @PathVariable String random) throws IOException, ContentDeletedException
{
    BufferedOutputStream bufferedOutputStream = null;
    try {
        //.............

        bufferedOutputStream            = new BufferedOutputStream(response.getOutputStream());
        ByteBuffer          byteBuffer  = imgService.getProfilePhoto(cqlSession, column, profileId);
        if(byteBuffer==null) throw new ContentDeletedException();
        byte                bytes[]     = new byte[byteBuffer.remaining()];

        byteBuffer.get(bytes, 0, bytes.length);
        bufferedOutputStream.write(bytes);
    } catch (IOException ex) {ex.printStackTrace();}
    finally{if(bufferedOutputStream!=null) bufferedOutputStream.close();}
    throw new ContentDeletedException();
}

如果byteBuffernull,它会在tomcate日志中抛出ContentDeletedException,但在浏览器控制台中,它仍会显示200OK响应。所以在客户端,它显示空图像。

为什么呢?它不应该抛出200 OK状态。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我这样做:

if(byteBuffer==null){
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
else{
    byte  bytes[]     = new byte[byteBuffer.remaining()];            
    byteBuffer.get(bytes, 0, bytes.length);
    bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
    bufferedOutputStream.write(bytes);
}