【问题标题】:How to show server (Java) Exception message in React.js如何在 React.js 中显示服务器(Java)异常消息
【发布时间】:2020-04-29 09:09:54
【问题描述】:

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

情况: 用户想要执行一些操作(通过 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 动作块中设置按摩值来显示异常消息。

输出

err.data: ""
err.message: undefined

还有,

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

请帮忙。

【问题讨论】:

标签: java reactjs spring rest react-redux


【解决方案1】:

默认情况下 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 advice 并编写自定义异常处理会更好。在你的情况下是这样的

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

【讨论】:

  • 您好,感谢您的回复。根据需要在ExceptionRestResponse 中添加constructor。 CE 在@Value,'注释@Value 不允许用于此位置'。
  • 为了简洁起见,我使用了@Value。您可以将其替换为构造函数和吸气剂。或者您必须将 lombok 插件安装到您的 IDE。我测试了我在我的机器上发布的代码示例,所以一切都应该工作。
  • 删除了@Value。调试了代码,我可以看到方法 handleCustomException 正在执行,但在 UI 中看不到消息。你能告诉我对象err中属性message的完整路径是什么吗?
  • code,message 的 getter/setter 需要以解决上述问题。
  • 确保 @Value 注解来自 lombok 而不是 Spring。您还可以通过工作示例查看 - mkyong.com/spring-boot/spring-rest-error-handling-examplebaeldung.com/spring-mvc-controller-custom-http-status-code
【解决方案2】:

您可以使用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"
     ....
}

更多:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/ResponseStatusException.html

【讨论】:

  • 感谢您的回复。找不到名称为 ResponseStatusException 的任何类型。你能指定包裹吗?
  • 请查看我在答案中包含的底部链接。从 5.0 开始,它就是 Spring Framework 的一部分。
  • ResponseStatusException 从 5.0 开始,但我们使用的是 4.3.x。否则会是一个不错的选择。
  • 您可以在此处查看其他解决方案,包括较旧的 Spring 版本:baeldung.com/exception-handling-for-rest-with-spring
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
  • 2013-01-02
  • 1970-01-01
  • 2011-09-01
  • 2020-05-30
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多