如果文件太大,我会从服务器代码(在 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 中的开发模式视图报告了“未捕获的异常”类型的错误,这表明我在检测它方面确实做得不好。
谁能告诉我如何正确捕获异常,以及我使用的解决方法是否有意义?
谢谢!