用户未填写任何评价
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);
}
}