栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring-boot 统一异常处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;


@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 {
    //错误码
    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;


public class ResponseUtils {
    public static ResponseDto error(Object object) {
        ResponseDto 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;


@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);
     }
}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号