java - Servlet 发送 400 错误数据

标签 java angularjs servlets

我希望我的 servlet 返回带有数据的错误代码,以便客户端可以向用户指出请求出了什么问题。 如果数据无效时出现异常:

catch (UnvaildInputException UIE) {
            UnvaildCodes unvaildCode = UIE.getUnvaildCode(); //code 1 for example
            System.out.println(unvaildCode.getKey() + "-" + unvaildCode.getValue()); //prints error key-val
            System.out.println(unvaildCode.getValue());
            response.getWriter().print(HttpServletResponse.SC_BAD_REQUEST +":"+unvaildCode.getValue()); //trying to write a string as data
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST); //400
        }

现在在客户端(angularjs)我正在尝试访问数据:

httpService.sendPost(vm.details, '/some/url').then(function (response){
        $log.log(response);
        $log.log(response.data);
});

错误:

TypeError: Cannot read property 'data' of undefined
    at formDirectiveJS.js:91
    at angular.min.js:126
    at m.$eval (angular.min.js:140)
    at m.$digest (angular.min.js:137)
    at m.$apply (angular.min.js:141)
    at g (angular.min.js:93)
    at t (angular.min.js:98)
    at XMLHttpRequest.u.onload (angular.min.js:99)

最佳答案

您需要在错误处理程序中处理错误,而不是在成功处理程序中。

来自https://stackoverflow.com/a/35458437/1842905

$http.get(url)
.then(function (response) {
    console.log('get',response)
})
.catch(function (data) {
    // Handle error here
});

关于java - Servlet 发送 400 错误数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45032381/

相关文章:

java - 在Windows中运行脚本后,模拟器需要自动关闭

javascript - Protractor 检查元素是否不存在

html - 如何在 CSS 中组合两个 Angularjs 表单验证指令条件?

javascript - Ng Click 在导航栏中不起作用

java - com.x.y.z 包不存在

java - 在 Java 中从 json 文件中删除 json 对象

java - Java字符集-如何从System.in获得正确的输入?

java - Swing JTree : It seems to be impossible to properly send treeStructureUpdated events to model listeners

sql - 在 SQL :query tag; why? JSTL 1.2 内部使用时,使用 AS 重命名 SQL SELECT 语句中的列名称失败

java - 如何让 Jetty 返回错误响应而不是假设 HTTP/0.9 请求?