SpringBoot全局异常处理

拟墨画扇 提交于 2020-02-26 17:35:58

主要操作 controller下面添加两个类
JacksonConfig
代码如下

package com.sansec.sanatom.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonConfig {

@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    //直接屏蔽掉值为null的参数
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objectMapper;
}

}

GlobalExceptionHandler

package com.sansec.sanatom.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.sansec.sanatom.utils.response.ExceptionResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
*

  • @author lvxingsheng

*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final SimpleDateFormat dateFormat=new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);
@ExceptionHandler(Exception.class)
ResponseEntity<?> handleException(Exception e){
ExceptionResponse response = new ExceptionResponse();
response.setStatus(“1”);
response.setAppId("");
response.setPreId("");
response.setMessage(“Exception msg=”+e.getMessage());
response.setTime(dateFormat.format(new Date()));
return new ResponseEntity(response,HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value=MethodArgumentNotValidException.class)
ResponseEntity<?> MethodArgumentNotValidHandler(MethodArgumentNotValidException e)
{
ExceptionResponse response = new ExceptionResponse();
StringBuilder builder = new StringBuilder();
for (FieldError error : e.getBindingResult().getFieldErrors()) {
builder.append(“errMsg=”);
builder.append(error.getDefaultMessage());
builder.append(",");
builder.append(error.getObjectName());
builder.append("=");
builder.append(error.getRejectedValue());
builder.append(";");
}
response.setStatus(“1”);
response.setTime(dateFormat.format(new Date()));
response.setMessage(builder.toString());
return new ResponseEntity(response,HttpStatus.INTERNAL_SERVER_ERROR);
}
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!