SpringBoot自定义返回code值

关于HttpStatus

在SpringBoot中关于状态码有一个枚举类型,如下。

public enum HttpStatus {
    CONTINUE(100, "Continue"),
    SWITCHING_PROTOCOLS(101, "Switching Protocols"),
    PROCESSING(102, "Processing"),
    CHECKPOINT(103, "Checkpoint"),
    OK(200, "OK"),
    ...
}

通过以下三种方法均可实现

1. 通过@ResponseStatus注解

eg:

@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR,reason="server error")
public class ServerException extends Exception {
	...
}

在全局异常捕捉的类中定义,可以自定义特定的异常来返回特定的状态码。

2. 修改responsestatus属性

eg:

@RequestMapping(value = "/index", method = RequestMethod.GET)
public void index(HttpServletResponse response) throws IOException{
    response.setStatus(500);
    response.getWriter().append("server error");
}

需要多加response参数,但这样的控制器都必须为void,有诸多限制。

3. ResponseEntity

eg:

@RequestMapping(value = "/user", method = RequestMethod.GET)
public ResponseEntity<Map<String,Object>> getUser() throws IOException{
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("name", "user");
    return new ResponseEntity<Map<String,Object>>(map,HttpStatus.OK);
}

这样返回类型就只能是ResponseEntity


前后端分离开发一般都会自定义返回的数据格式。
都会包含msg,code,data三个属性。
可用上述思路实现以下工具类。实现自定义返回的状态码,需将返回格式设置为以下类的格式,将返回数据传入data

JSONResult.java

public class JSONResult<T> extends ResponseEntity<Message> {

    public JSONResult(HttpStatus status) {
        super(status);
    }

    public JSONResult(String code, String msg, T data) {
        super(Message.custom(code, msg, data), Message.num2HttpStatus(code));
    }

    public JSONResult(String code, String msg) {
        super(Message.custom(code, msg), Message.num2HttpStatus(code));
    }

    public static <T> JSONResult<T> success(T data) {
        return new JSONResult("200", "成功", data);
    }

    public static <T> JSONResult<T> failed(T data) {
        return new JSONResult("422", "失败", data);
    }

    public static <T> JSONResult<T> failMsg(String msg) {
        return new JSONResult("422", msg);
    }

    public static <T> JSONResult<T> custom(String code, String msg, T data) {
        return new JSONResult(code, msg, data);
    }
}

class Message<T> {

    String status;
    //向前端返回的内容
    String message;

    T data;

    public Message() {
    }

    public Message(String status, String message) {
        this.status = status;
        this.message = message;
    }

    public Message(String status, String message, T data) {
        this.data = data;
        this.status = status;
        this.message = message;
    }

    public static <T> Message<T> custom(String status, String message, T data) {
        return new Message(status, message, data);
    }

    public static <T> Message<T> custom(String status, String message) {
        return new Message(status, message);
    }

    public static HttpStatus num2HttpStatus(String code) {
        HttpStatus status = HttpStatus.NOT_FOUND;
        for (HttpStatus httpStatus : HttpStatus.values()) {
            boolean b = Integer.parseInt(code) == httpStatus.value();
            if (b) {
                return httpStatus;
            }
        }
        return status;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

}

 

通过继承ResponseEntity类来实现自定义返回类的自定义状态码返回。

#@Le.Hao#

帮助到您请点赞关注收藏谢谢!!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
SpringBoot中,我们可以通过自定义异常来处理业务逻辑中出现的异常情况。以下是实现步骤: 1. 自定义异常类 在项目包中创建一个自定义的异常类,需要继承Exception或RuntimeException。 ``` public class CustomException extends RuntimeException { private int code; private String message; public CustomException(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } } ``` 2. 异常处理类 在项目包中创建一个异常处理类,需要使用@ControllerAdvice和@ExceptionHandler注解,通过指定异常类来捕获异常并处理。 ``` @ControllerAdvice public class CustomExceptionHandler { @ExceptionHandler(CustomException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result handleCustomException(CustomException e) { return new Result(e.getCode(), e.getMessage(), null); } } ``` 3. 统一响应对象 在项目包中创建一个统一响应对象类,用于统一封装响应信息。 ``` public class Result<T> { private int code; private String message; private T data; public Result(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public String getMessage() { return message; } public T getData() { return data; } } ``` 以上就是springboot自定义异常的实现步骤。在业务逻辑中抛出自定义异常即可触发异常处理类中的处理方法,并返回统一响应对象。这样可以统一处理异常并返回规范化的响应信息,方便前端或其他系统的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@lehao

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

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

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

打赏作者

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

抵扣说明:

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

余额充值