HttpServlet引发的GWT捕获异常

时间:2012-10-19 15:14:55

标签: java forms gwt servlets exception-handling

从服务器代码(在HttpServlet中)如果文件太大,我会抛出异常:

 public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
 ...
 // Check if the blob has correct size, otherwise delete it
 final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
 long size = blobInfo.getSize();
 if(size > 0 && size <= BasicConstants.maxImageSize){
    res.sendRedirect("/download?blob-key=" + blobKey.getKeyString());
 } else { // size not allowed
    bs.delete(blobKey);
    throw new RuntimeException(BasicConstants.fileTooLarge);
 }

从客户端代码我缺少成功捕获此代码段的异常:

try {
    uploadForm.submit(); // send file to BlobStore, where the doPost method is executed
} catch (Exception ex) {
    GWT.log(ex.toString());
}

然而,从这个其他客户端代码片段中,我以某种方式检测异常何时抛出了一个我完全不信任的丑陋的解决方法:

uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

    @Override
public void onSubmitComplete(SubmitCompleteEvent event) {
// This is what gets the result back - the content-type *must* be
// text-html
String imageUrl =event.getResults();

    // This ugly workaround apparently manages to detect when the server threw the exception
if (imageUrl.length() == 0) { // file is too large
  uploadFooter.setText(BasicConstants.fileTooLarge);
} else { // file was successfully uploaded
       ...
    }

Eclipse中的“开发模式”视图报告了类型&#34;未捕获异常&#34;的错误,这表明我在检测它时确实做得不好。

任何人都可以告诉我如何正确捕捉异常,如果我使用的解决方法有意义吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

您的第一次尝试

try {
    uploadForm.submit(); // send file to BlobStore, where the doPost method is executed
} catch (Exception ex) {
    GWT.log(ex.toString());
}

不起作用,因为submit()不会等到浏览器收到响应(这是异步调用)。

uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

  @Override
  public void onSubmitComplete(SubmitCompleteEvent event) {
    ...

这里实际上是从服务器收到响应。但它是表单提交,而不是GWT-RPC调用,因此结果只是纯文本,而不是GWT Java对象。

当你在Servlet中抛出RuntimeException时,服务器只会发送一个带有错误代码的响应(可能是'500',但理想情况下使用Firebug或Chrome Developer Tools中的“Network”选项卡来查看实际的响应和响应代码。)因此,在成功案例中,您将获得URL,否则响应为空。

可能的解决方案

您可以在服务器端捕获异常,并明确发送更好的描述:

public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

  try {

      ...
      if (...) {
        throw new MyTooLargeException();
      } else {
          ...
        res.getWriter().write("ok " + ...);
      }

  } catch (MyTooLargeException e) {
     res.getWriter().write("upload_size_exceeded"); // just an example string 
                                                    // (use your own)

     res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
  }
}

然后,在客户端上,检查

"upload_size_exceeded".equals(event.getResults()).