[英]How to show server (Java) Exception message in React.js
在抛出异常(由 Java 中的服务器)时,我无法看到设置的消息(在 React.js 捕获块中)。
情况:用户想要执行一些操作(通过 myService),一些验证 w.r.t 操作只能在后端完成,如果失败如何向用户显示失败的原因是什么?
服务(Java):
@GetMapping(path = {/*Servive_path*/}, produces = APPLICATION_JSON_VALUE)
public MyClass myService(@RequestParam String param) {
throw new RuntimeException("This is error message");
}
动作(React.js):
const myServive = (param) => {
return async (dispatch, getState) => {
return request({
url: ENDPOINTS.MY_SERVICE,
method: methods.GET,
params: { param }
})
.then(res => {
dispatch(saveResult(res));
dispatch(
notify({
title: "Successful",
message: "It was successfully.",
status: 200,
dismissAfter: CONFIG.NOTIFICATION_TIMEOUT
})
);
})
.catch(err => {
console.log("err.data: ", err.data); //Output-> err.data:
console.log("err.message: ", err.message); //Output-> err.message: undefined
dispatch(
notify({
title: "Some error occured",
message: **//Want to set the error message**,
status: "error",
dismissAfter: CONFIG.NOTIFICATION_TIMEOUT
})
);
});
};
};
希望通过在 catch 动作块中设置按摩值来显示异常消息。
Output
err.data: ""
err.message: undefined
还,
err.status: 500
err.request.response: ""
err.request.responseText: ""
err.request.responseType: ""
err.request.status: 500
err.request.statusText: ""
请帮忙。
默认情况下,如果出现异常 Spring 返回 http 状态 500,Content-Type: text/html;charset=UTF-8并生成带有错误描述的 html 页面。 您的错误描述将在此页面的最后一行之后
<div>There was an unexpected error (type=Internal Server Error, status=500).</div>
看起来像
<div>This is error message</div>
当然,您可以在代码中编写拐杖并使用 React 解析此页面,但我不建议这样做。 最好添加Controller 建议并编写自定义异常处理。 在你的情况下是这样的
import lombok.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ErrorHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ExceptionRestResponse handleCustomException(Exception exception) {
return new ExceptionRestResponse(500, exception.getMessage());
}
@Value
public static class ExceptionRestResponse {
int code;
String message;
}
}
然后你会得到 Content-Type: application/json的响应,看起来像
{
"code": 500,
"message": "This is error message"
}
您可以使用ResponseStatusException
将错误消息发送到reactjs
。
@RequestMapping(method = RequestMethod.GET, value = "/get")
public List<MyInfo> getInfo(){
try {
// code to return
} catch (InvalidObjectException | InvalidOperationException | OperationNotPermittedException | UserPermissionNotAvailableException e) {
// throwing custom exceptions
throw new ResponseStatusException(HttpStatus.FORBIDDEN, e.getMessage(), e);
}
catch (Exception e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
}
}
您可以使用特定的错误消息代替e.getMessage()
。
运行console.error(error)
以查看错误响应的结构并相应地显示它。 错误响应可能如下所示:
"error" : {
"status": 403,
"statusText": "FORBIDDEN",
"message": "User does not have permission to perform this operation",
"timestamp": "2020-05-08T04:28:32.917+0000"
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.