自定义返回结果类

现在restful风格的接口返回结果一般都是采用json格式,这里继承HashMap封装一下,返回code和msg。代码如下:
package com.magic.lang;

import java.util.HashMap;

/**
 * @author 刘俊重
 * @Description 封装后台向前端返回的数据
 */
public class WebResult extends HashMap<String,Object>{

    public WebResult(){
        put("code",200);
    }

    /**
     * @Description 返回成功结果
     * @Author 刘俊重
     */
    public static WebResult ok(){
        return new WebResult();
    }

    public static WebResult ok(String msg){
        WebResult result = new WebResult();
        result.put("msg",msg);
        return result;
    }

    public static WebResult ok(String code,String msg){
        WebResult result = new WebResult();
        result.put("code",code);
        result.put("msg",msg);
        return result;
    }
    /**
     * @Description 返回错误
     * @Author 刘俊重
     */
    public static WebResult error(){
        return error(500,"未知错误,请稍后重试!");
    }

    public static WebResult error(String msg){
        return error(500,msg);
    }

    public static WebResult error(int code,String msg){
        WebResult result = new WebResult();
        result.put("code",code);
        result.put("msg",msg);
        return result;
    }

    public WebResult put(String key,Object value){
        super.put(key,value);
        return this;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了自定义异常处理的功能,可以根据不同的异常返回不同的响应结果。下面是一个示例代码,演示了如何在Spring Boot中自定义异常处理: 1. 创建一个自定义异常,继承自Exception,并添加需要展示的信息等。例如,创建一个名为CustomException的: ```java public class CustomException extends Exception { private String message; public CustomException(String message) { this.message = message; } public String getMessage() { return message; } } ``` 2. 创建一个全局异常处理,用于处理所有的异常情况。例如,创建一个名为GlobalExceptionHandler的: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage()); } @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error"); } } ``` 在上述代码中,使用@ControllerAdvice注解标记全局异常处理,@ExceptionHandler注解用于指定处理特定异常的方法。handleCustomException方法用于处理CustomException异常,返回一个带有自定义异常信息的响应实体;handleException方法用于处理其他未处理的异常,返回一个带有"Internal Server Error"信息的响应实体。 3. 在控制器中抛出自定义异常。例如,在一个控制器方法中抛出CustomException异常: ```java @GetMapping("/custom-exception") public ResponseEntity<String> throwCustomException() throws CustomException { throw new CustomException("Custom Exception"); } ``` 在上述代码中,当访问"/custom-exception"路径时,将抛出CustomException异常。 通过以上步骤,你可以在Spring Boot中自定义异常处理,根据不同的异常返回不同的响应结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值