spring-boot 统一异常处理

package com.github.binarywang.demo.wx.mp.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author chenkang
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseDto getException() {
        return ResponseUtils.error("出错了");
    }
}
package com.github.binarywang.demo.wx.mp.controller;

import lombok.Data;

@Data
public class ResponseDto<T> {
    //错误码
    private String code;
    //提示信息
    private String msg;
    //具体的内容
    private T data;
    public ResponseDto() {
    }
    public ResponseDto(String code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }
    //getter和setter方法。。。
}
package com.github.binarywang.demo.wx.mp.controller;

/**
 * @author chenkang
 */
public class ResponseUtils {
    public static ResponseDto error(Object object) {
        ResponseDto<Object> objectResponseDto = new ResponseDto<>();
        objectResponseDto.setCode("200");
        objectResponseDto.setMsg("请求失败");
        objectResponseDto.setData(object);
        return objectResponseDto;
    }
}
package com.github.binarywang.demo.wx.mp.controller;

import com.github.binarywang.demo.wx.mp.entity.ContactUser;
import com.github.binarywang.demo.wx.mp.service.IUserInfoService;
import com.github.binarywang.demo.wx.mp.utils.CommonUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author chenkang
 * 微信素材管理controler
 */
@AllArgsConstructor
@RestController
@RequestMapping(value ="/wx/test/")
public class TestController {
    private final IUserInfoService userInfoService;
    @GetMapping("/userInfo")
    public void userInfo() {
        ContactUser userInfo = new ContactUser();
         // TODO 获取不到微信号,暂时使用昵称代替
        userInfo.setCreateTime(new Date(Long.parseLong(String.valueOf(System.currentTimeMillis()))));
        userInfo.setGender(CommonUtils.getGender(null));
        throw new RuntimeException();
//        userInfoService.save(userInfo);
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值