欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

#后端#项目#自定义接口异常处理

程序员文章站 2022-04-24 08:13:41
...

常用接口异常整理


package com.lyr.cakemanagerv2.config;

import com.alibaba.fastjson.JSONObject;
import dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
 
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;

import javax.xml.bind.ValidationException;
 

/**
 * @Author lyr
 * @create 2020/7/30 16:31
 */
@RestControllerAdvice
@Order(-20)
@Slf4j
public class WebExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public Result exceptonShow(Exception ex) {

        log.error("服务器 基础异常 Exception {} {}",ex.getMessage(),ex.getClass());
        // ex.printStackTrace();
        return Result.from("服务异常",200);

    }
    @ExceptionHandler(IllegalArgumentException.class)
    public Result illegalArgument(IllegalArgumentException ex) {
        log.info("err {}",ex.getMessage());
        // return  new Result()
        //         .message("#@@ illegal argument>"+ex.getMessage())
        //         .data("err")
        //         .build();
        return Result.from("illegal argument ",500);
    }


    // @ExceptionHandler(MethodNotSupportedException.class)
    // public ResultDTO methodNotSupport(MethodNotSupportedException ex) {
    //     log.error("服务器 请求方法不正确 {}",ex.getMessage());
    //     // ex.printStackTrace();
    //     return ResultDTO.<ResultCode>builder()
    //             .data(ResultCode.ERROR)
    //             .message("&接口不支持的请求方法")
    //             .code(500)
    //             .build();
    //
    // }
    // @ExceptionHandler(ServiceException.class)
    // public Result serviceException(ServiceException ex) {
    //     log.error("服务器严重异常 {}",ex.getMessage());
    //     return Result.from("")
    // }


    @ExceptionHandler(WebExchangeBindException.class)
    public  Result<Object> missingValue(WebExchangeBindException ex) {
        log.error("服务器 参数绑定异常 {}",ex.getMessage());
        //Mono.just
        //返回 参数缺失的信息给前端
        return  Result.from("%参数绑定异常",505);

    }


    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result methodMissParm(MissingServletRequestParameterException ex) {
        log.error("服务器 参数绑定异常 {}",ex.getMessage());
        //Mono.just
        //返回 参数缺失的信息给前端
        return (Result.from("!请求参数缺失",404));

    }




    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<JSONObject> nullPointerExceptionHandler(NullPointerException ex) {
        log.error("nullPointerExceptionHandler, msg:{}, exception:{}", ex.toString(), ex.getMessage());
        JSONObject response = new JSONObject();
        response.put("message", "@nptr,Internal Server Error!");
        return Result.from("err",505,response);
    }


    /*----- REQUEST ERROR -----*/
    @ExceptionHandler({ HttpMessageNotReadableException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<JSONObject> requestNotReadable(HttpMessageNotReadableException ex) {

        log.error("HttpMessageNotReadableExceptionHandler, msg:{}, exception:{}", ex.toString(), ex.getMessage());
        JSONObject response = new JSONObject();
        response.put("message", "Bad Request,not readable");
        return Result.from("err",500,response);
    }

    @ExceptionHandler({ValidationException.class, BindException.class, MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result validateError(Exception ex) {
        return Result.from("前端参数不正确",500);
    }



    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result httpNotSupportexceptonShow(HttpRequestMethodNotSupportedException ex) {
        log.error("httpMethod not Support Exception {}",ex.getMessage());
        // ex.printStackTrace();
        return Result.from("http method not support",404);

    }


}



下面是DTO 对象


package dto;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @Author lyr
 * @create 2020/7/14 0:53
 */
@Data
@Accessors(chain = true)
public class Result<T> {

    private Boolean flag;//是否成功
    private Integer code;//返回码
    private String message;//返回消息


    private T data;//返回数据

    public static<T> Result<T> from(String msg,Integer code,Boolean flag,T data) {
        return from(msg,code,data).setFlag(flag);
    }
    public static <Object> Result<Object> from(String msg,Integer code) {
        return new Result<Object>().setMessage(msg).setCode(code);
    }

    public static<T> Result<T> from(String msg,Integer code,T data) {
        return Result.<T>from(msg,code)
                .setData(data);
    }


}


相关标签: CRUD