spring boot 全局异常处理

Posted Alex_zhuang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot 全局异常处理相关的知识,希望对你有一定的参考价值。

0.使用 @ ExceptionHandler 注解(Controller层面上)

   严格来说不是全局,是单类异常处理,进行异常处理的方法必须与出错的方法在同一个Controller里面。

package com.lvjing.controller;

import com.alibaba.fastjson.JSON;
import com.lvjing.bean.ResponseBeanWithCount;
import com.lvjing.common.ResponseBean;
import com.lvjing.dao.CommuteLogMapper;
import com.lvjing.domain.CommuteLog;
import lombok.extern.java.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author:ZY
 * @Descirption:
 * @Date: Created by ZY on 2018/1/3.
 * @Modified By:
 */
@Log
@RestController
@RequestMapping(value="/commute")
public class CommuteLogController {

    private CommuteLogMapper commuteLogMapper;
    @Autowired
    private void setCommuteLogMapper(CommuteLogMapper commuteLogMapper){
        this.commuteLogMapper = commuteLogMapper;
    }

    /**
     * @Description: 查询进出电子围栏
     * @author: ZY
     * @param: [paraMap]
     * @return: com.lvjing.common.ResponseBean
     * @Date: 2019/1/3
     */
    @RequestMapping(value = "/getCommuteLogList", method = RequestMethod.POST)
    public ResponseBeanWithCount getDeviceWarningLogList(@RequestBody Map<String, Object> paraMap) throws Exception {
        log.info("查询进出电子围栏人员列表,参数="+ JSON.toJSONString(paraMap));
        if ("0".equalsIgnoreCase(paraMap.get("id").toString())){
            throw new Exception("ID==0");
        }

        CommuteLog commuteLog = JSON.parseObject(JSON.toJSONString(paraMap), CommuteLog.class);
        if (paraMap.isEmpty()) {
            return new ResponseBeanWithCount(-1, "查询条件不能为空", 0, null);
        }
        int count = commuteLogMapper.queryCount(commuteLog);
        List<CommuteLog> deviceWarningLogs = commuteLogMapper.query(commuteLog);
        log.info("查询进出电子围栏人员列表,返回值="+ JSON.toJSONString(deviceWarningLogs));
        return new ResponseBeanWithCount(0, "查询成功!", count, deviceWarningLogs);
    }
    @ExceptionHandler({Exception.class})
    private ResponseBeanWithCount handleException(Exception e){
        e.printStackTrace();
        log.info(e.getMessage());
        return new ResponseBeanWithCount(-1, "查询失败", 0, null);
    }

}

 

 

 

1.

以上是关于spring boot 全局异常处理的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot-全局异常处理

峰哥说技术系列-9 Spring Boot ControllerAdvice处理全局异常 - 副本

Spring Boot2 系列教程(十三)Spring Boot 中的全局异常处理

spring boot 全局异常处理

Spring Boot系列SpringBoot全局异常处理数据校验

Spring Boot入门——全局异常处理