跳至主要內容

统一异常处理

chanchaw小于 1 分钟languagejava

HttpMessageNotReadableException

前端传递的参数在日期类型的属性上如果格式和后端要求的不一致则后端会报异常 HttpMessageNotReadableException,在统一异常处理中截取该异常并返回给前端可以方便看到异常信息快速处理问题。下面代码还包含了业务异常的截取。

package com.xdf.showa.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * @ClassName:GlobalExceptionHandler
 * @Description:TODO
 * @Author:chanchaw
 * @Date:2019-12-23 8:37
 * @Version:1.0
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    // 在请求接口反序列化之前将字符串类型的日期时间参数根据指定格式转换为日期类型
    /*
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
     */

    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    // 返回这个错误码会导致前端认为服务器内部错误 - INTERNAL_SERVER_ERROR是500表示服务器内部错误
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public JsonResult handleBusinessException(BusinessException ex) {
        String msg = ex.getMsg();
        return JsonResult.error(msg);
    }

    //@ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.OK)
    public JsonResult handleValidException(HttpMessageNotReadableException exception) {
        log.error(exception.getMessage());
        return JsonResult.error(exception.getMessage());
    }
}