[英]GWT Catching exception thrown by HttpServlet
如果文件太大,則從服務器代碼(在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中的“開發模式”視圖報告“未捕獲的異常”類型的錯誤,這表明我在檢測它方面確實做得不好。
誰能告訴我如何正確捕獲異常,以及我使用的解決方法是否有意義?
謝謝!
您的第一次嘗試
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開發者工具中的“網絡”標簽查看實際的響應和響應代碼。)因此,在成功的情況下,您將獲得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()).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.