2016-08-16 61 views
0

我一直在我的前端界面中使用Backbone以支持Spring的Java程序。在頁面上,用戶提交一個文件,然後得到處理,他們得到一個下載作爲回報。當一切運行良好的Java代碼,他們得到下載,因爲他們應該。但是,如果出現錯誤,它會停止,並且頁面會返回一個警告框,指示「未定義」。jQuery警告'未定義'的錯誤,而不是Java/Spring異常詳細信息

我希望能夠返回交互式錯誤,以便用戶可以知道哪裏出了問題。我有一個看起來像這樣的RestExceptionHandler類,我想在警告框中將例外返回給用戶。

@Slf4j 
@ControllerAdvice 
public abstract class RestExceptionHandler { 

    @ExceptionHandler({ Exception.class }) 
    public ResponseEntity<String> handleGeneralException(final Exception exception) { 
     logException("General Exception : ", exception); 
     return new ResponseEntity<String>(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); 
    } 

    @ExceptionHandler({ IllegalArgumentException.class, JsonException.class }) 
    public ResponseEntity<String> handleBadRequestException(final Exception exception) { 
     logException("Bad Request Exception : ", exception); 
     return new ResponseEntity<String>(exception.getMessage(), HttpStatus.BAD_REQUEST); 
    } 

    private void logException(final String info, final Exception exception) { 
     log.error(info + exception.getMessage() + Throwables.getStackTraceAsString(exception)); 
    } 
} 

關於JavaScript的一些背景,我寫的,當用戶點擊提交事件的功能。它從頁面輸入,將它設置爲骨幹的型號,然後...

// post to output and return download 
    model.url = window.location + "output"; 
    model.save({}, 
    { 
     error: function (model, response) { 
      alert(response.message); 
     }, 
    success: function (model, response) { 
     // download stuff goes here ... 

這裏的春天控制器...

@RestController 
public class ValidateController extends RestExceptionHandler { 

    @Autowired 
    private OntologyValidate validate; 

    @RequestMapping(value="/output", method= RequestMethod.POST) 
    public @ResponseBody Object graph(@RequestBody String body) throws Exception { 

     JSONObject jo = new JSONObject(body); 

     // get user input arguments from body 
     JSONArray JSONinputFiles = jo.getJSONArray("inputFile"); 
     JSONArray JSONfileFormats = jo.getJSONArray("fileFormat"); 
     JSONArray JSONfileNames = jo.getJSONArray("fileName"); 

     String label = jo.getString("label"); 
     String description = jo.getString("description"); 
     String fin = ""; 

     // Do processing stuff here 

     jo.put("results", fin); 
     return new ResponseEntity<Object>(jo.toString(), HttpStatus.OK); 

    } 
} 

我很高興能提供必要的任何額外的代碼。

回答

0

回答了我自己的問題!

而不是試圖從response錯誤信息,我需要從xhr得到它。異常處理程序不需要返回響應實體,只是一個例外字符串(看起來也乾淨多了)

@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR) 
@ExceptionHandler({ Exception.class }) 
public String handleGeneralException(final Exception e) { 
    logException("General Exception : ", e); 
    return e.toString(); 
} 

然後我的JavaScript提醒消息,如果的HTTPStatus都不行(不知道如果模型並且響應是必要的):

error: function (model, response, xhr) { 
    var json = JSON.stringify(xhr.xhr.responseText); 
    json = json.replace(/"/g, ""); 
    alert(json); 
}, 

Stringify以雙引號返回消息,所以我只是用乾淨的消息替換它們。控制器中沒有任何東西需要改變。