Spring:统一结果私有属性造成的前端无法访问异常报错问题

用户未填写任何评价

1.问题复现

(1)看一段代码

controller:

import lombok.extern.slf4j.Slf4j;
import org.ljy.testdemo.common.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {

    @RequestMapping("/hello")
    public String hello() {
        int a = 10/0;
        return "hello";
    }

    @RequestMapping("/heihei")
    public Result heihei() {
        return Result.fail("只因你实在是太美~");
    }
}

common:

public class Result {
    private String message;
    private int code;

    public Result(String message,int code) {
        this.message = message;
        this.code = code;
    }

    public static Result fail(String message) {
        return new Result(message,1314);
    }
    
}

exception:

import lombok.extern.slf4j.Slf4j;
import org.ljy.testdemo.common.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@ResponseBody
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler
    public Result exception(Exception e) {
        log.error(e.getMessage(), e);
        return Result.fail(e.getMessage());
    }
}

通过postman进行访问:

访问第二个接口:

(2)问题的原因

由于Result中的属性被设置成了private,所以当以其作为返回结果时,前端无法直接访问Result中的属性,进而报错。作为后端开发人员,只需要知道这样会导致前端无法访问到就行了。

2.解决的方法

因为前端无法直接访问属性,所以我们要做的就是让前端可以访问到属性即可

(1)最推荐做法:加上@Data注解

@Data
public class Result {
    private String message;
    private int code;

    public Result(String message,int code) {
        this.message = message;
        this.code = code;
    }

    public static Result fail(String message) {
        return new Result(message,1314);
    }

}

 

(2)提供get方法

public class Result {
    private String message;
    private int code;

    public Result(String message,int code) {
        this.message = message;
        this.code = code;
    }

    public static Result fail(String message) {
        return new Result(message,1314);
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

(3)不推荐:private改成public

public class Result {
    public String message;
    public int code;

    public Result(String message,int code) {
        this.message = message;
        this.code = code;
    }

    public static Result fail(String message) {
        return new Result(message,1314);
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码小娥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值