[英]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.