如何在 React.js 中显示服务器(Java)异常消息 [英] How to show server (Java) Exception message in React.js

查看:46
本文介绍了如何在 React.js 中显示服务器(Java)异常消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法看到在抛出异常时设置的消息(在 React.js catch 块中)(通过 Java 中的服务器).

情况: 用户想要执行一些操作(通过 myService),一些验证操作只能在后端完成,如果失败了如何向用户显示失败的原因?

服务(Java):

@GetMapping(path = {/*Servive_path*/},产生 = APPLICATION_JSON_VALUE)公共 MyClass myService(@RequestParam String param) {throw new RuntimeException("这是错误信息");}

操作(React.js):

const myServive = (param) =>{return async (dispatch, getState) =>{返回请求({网址:ENDPOINTS.MY_SERVICE,方法:methods.GET,参数:{参数}}).then(res => {调度(保存结果(res));派遣(通知({title: "成功",消息:成功了.",状态:200,解雇后:CONFIG.NOTIFICATION_TIMEOUT}));}).catch(错误 => {console.log("err.data: ", err.data);//输出->错误数据:console.log("err.message: ", err.message);//输出->错误消息:未定义派遣(通知({标题:发生了一些错误",message: **//要设置错误信息**,状态:错误",解雇后:CONFIG.NOTIFICATION_TIMEOUT}));});};};

想要通过在动作的catch块中设置massage中的值来显示异常消息.

输出

err.data: ""错误消息:未定义

还有,

err.status: 500err.request.response: ""err.request.responseText: ""err.request.responseType: ""err.request.status: 500err.request.statusText: ""

请帮忙.

解决方案

默认情况下,Spring 会在出现异常时返回 http 状态 500,内容类型为:text/html;charset=UTF-8 和生成带有错误描述的 html 页面.您的错误描述将​​在本页最后一行

之后

出现意外错误(类型=内部服务器错误,状态=500).</div>

看起来像

这是错误信息

当然,您可以在代码中编写拐杖并使用 React 解析此页面,但我不建议这样做.添加控制器建议并编写自定义异常处理会更好.在你的情况下是这样的

import lombok.Value;导入 org.springframework.http.HttpStatus;导入 org.springframework.web.bind.annotation.ExceptionHandler;导入 org.springframework.web.bind.annotation.ResponseStatus;导入 org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice公共类 ErrorHandler {@ExceptionHandler(Exception.class)@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)public ExceptionRestResponse handleCustomException(异常异常){返回新的 ExceptionRestResponse(500, exception.getMessage());}@价值公共静态类 ExceptionRestResponse {国际代码;字符串消息;}}

然后你会得到 Content-Type: application/json 的响应,它看起来像

<代码>{代码":500,"message": "这是错误信息"}

I am not able to see the message (in React.js catch block) set while throwing Exception (by server in Java).

Situation: User wants to perform some action (via myService), some verification w.r.t action can be done only on back-end, if that fails how to show the user what was the reason of failure?

Service (Java):

@GetMapping(path = {/*Servive_path*/}, produces = APPLICATION_JSON_VALUE)
public MyClass myService(@RequestParam String param) {
    throw new RuntimeException("This is error message");
}

Action (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
          })
        );
      });
  };
};

Want to show the exception message by setting value in massage in catch block of action.

Output

err.data: ""
err.message: undefined

Also,

err.status: 500
err.request.response: ""
err.request.responseText: ""
err.request.responseType: ""
err.request.status: 500
err.request.statusText: ""

Please help.

解决方案

By default in case of exception Spring return http status 500 with Content-Type: text/html;charset=UTF-8 and generates html page with error description. Your error description will be in the last line of this page after

<div>There was an unexpected error (type=Internal Server Error, status=500).</div>

and will look like

<div>This is error message</div>

Of course you can write crutch in your code and parse this page using React, but I wouldn't recommend so. It's much better to add Controller advice and write custom exception handling. In your case something like this

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;
    }
} 

Then you will get response with Content-Type: application/json which will look like

{
    "code": 500,
    "message": "This is error message"
} 

这篇关于如何在 React.js 中显示服务器(Java)异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆