0

サーバーコード(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の開発モードビューは、「キャッチされない例外」タイプのエラーを報告します。これは、私がそれを検出するのに本当に悪い仕事をしていることを示唆しています。

誰かが例外を適切にキャッチする方法を教えてもらえますか、そして私が使用している回避策が意味をなすかどうか。

ありがとう!

4

1 に答える 1

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呼び出しではないため、結果はプレーンテキストであり、GWTJavaオブジェクトではありません。

サーブレットでRuntimeExceptionをスローすると、サーバーはエラーコード(おそらく「500」)を含む応答を送信するだけですが、実際の応答と応答コードを確認するには、FirebugまたはChromeデベロッパーツールの[ネットワーク]タブを使用するのが理想的です。したがって、成功した場合は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()).
于 2012-10-19T17:52:10.977 に答える