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

常用接口异常整理


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);
    }


}


补充: 拦截404页面

spring:
  profiles:
    active: dev
  servlet:
    multipart:
      max-file-size: 3221225472
  mvc:
    format:
      date: yyyy-MM-dd HH:mm:ss

    throw-exception-if-no-handler-found: true
  resources:
    add-mappings: false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值