[Day 17]独自一人的全端攻略(後端篇)

挑战目标: MockNative Camp


今天来自定义Spring ExceptionHandler,首先先建立handlerexception资料夹,并新增这些档案
https://ithelp.ithome.com.tw/upload/images/20211002/20140358pPtw3KVN86.png

ClientHttpServerErrorException.java

package com.mock.nativecamp.handler;

import com.fasterxml.jackson.databind.exc.ValueInstantiationException;
import com.mock.nativecamp.exception.ClientHttpServerErrorException;
import com.mock.nativecamp.exception.TransactionNotFoundException;
import com.mock.nativecamp.payload.CommonResponse;
import com.mock.nativecamp.payload.sub.Info;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class ApiExceptionHandler {

    /**
     * Inquiry not found
     *
     * @param e
     * @return paymentMSErrorResponse
     */
    @ExceptionHandler(TransactionNotFoundException.class)
    @ResponseBody
    public Object handleNotFound(TransactionNotFoundException e) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setInfo(generateInfo("404", e.getMessage()));
        log.error("catch Not Found error: " + commonResponse.toString());
        return commonResponse;
    }

    /**
     * @param e
     * @return Object
     */
    @ExceptionHandler(ClientHttpServerErrorException.class)
    @ResponseBody
    public Object handleClientError(ClientHttpServerErrorException e) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setInfo(generateInfo(e.getMessage().split("\\s+")[0], e.getMessage()));
        log.error("catch  error: " + commonResponse.toString());
        return commonResponse;
    }

    @ExceptionHandler(ValueInstantiationException.class)
    @ResponseBody
    public Object handleValidError(ValueInstantiationException e) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setInfo(generateInfo("401", e.getOriginalMessage().split("problem: ")[1]));
        return commonResponse;
    }

    private Info generateInfo(String code, String message) {
        Info info = new Info();
        info.setStatus(code);
        info.setMessage(message);
        return info;
    }
}

TransactionNotFoundException.java

package com.mock.nativecamp.exception;


public class TransactionNotFoundException extends RuntimeException {

    public TransactionNotFoundException() {
    }

}

ValidException.java

package com.mock.nativecamp.exception;

import org.springframework.validation.Errors;

public class ValidException extends RuntimeException {

    private Errors errors;

    public ValidException(String message, Errors errors) {
        super(message);
        this.errors = errors;
    }

}

ApiExceptionHandler.java

package com.mock.nativecamp.handler;

import com.fasterxml.jackson.databind.exc.ValueInstantiationException;
import com.mock.nativecamp.exception.ClientHttpServerErrorException;
import com.mock.nativecamp.exception.TransactionNotFoundException;
import com.mock.nativecamp.payload.CommonResponse;
import com.mock.nativecamp.payload.sub.Info;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class ApiExceptionHandler {

    /**
     * Inquiry not found
     *
     * @param e
     * @return paymentMSErrorResponse
     */
    @ExceptionHandler(TransactionNotFoundException.class)
    @ResponseBody
    public Object handleNotFound(TransactionNotFoundException e) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setInfo(generateInfo("404", e.getMessage()));
        log.error("catch Not Found error: " + commonResponse.toString());
        return commonResponse;
    }

    /**
     * @param e
     * @return Object
     */
    @ExceptionHandler(ClientHttpServerErrorException.class)
    @ResponseBody
    public Object handleClientError(ClientHttpServerErrorException e) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setInfo(generateInfo(e.getMessage().split("\\s+")[0], e.getMessage()));
        log.error("catch  error: " + commonResponse.toString());
        return commonResponse;
    }

    @ExceptionHandler(ValueInstantiationException.class)
    @ResponseBody
    public Object handleValidError(ValueInstantiationException e) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setInfo(generateInfo("401", e.getOriginalMessage().split("problem: ")[1]));
        return commonResponse;
    }

    private Info generateInfo(String code, String message) {
        Info info = new Info();
        info.setStatus(code);
        info.setMessage(message);
        return info;
    }
}

ValueInstantiationException是lombok检查时错误的Exception,只要接住处理後就可以达成我们要的response

测试
https://ithelp.ithome.com.tw/upload/images/20211002/20140358vRrAWZPXY5.png
这样就可以透过新增自定义Exception在ExceptionHandler这边去做自定义response。


<<:  【没钱买ps,PyQt自己写】Day 17 / Project 制作标注 roi 工具, 开始导入 OpenCV 作为绘图引擎, 在图上画点并显示座标

>>:  Day17 NodeJS-Express II

Day 10 Template message in Messaging API

因为我这边群组团购机器人会用到的一些模板,所以在这篇文章介绍一下Template message,本...

你的 MVVM 不是你的 MVVM

相信各位也看了 N 个介绍 MVVM 的文章了吧,不知道你们有没有觉得大家所描述的 MVVM 是不是...

Day 03 认识你的消费者

为什麽要建立品牌的搜寻广告活动 让使用者在搜索您的商家时可以直接进到您的商家官网,避免当使用者在搜索...

op.29 《全领域》-全域开发实战 - 居家植物盆栽 Mvt IV (Flutter)

op.29 //今天脑袋暂时想不出干话 铁人赛也要来到尾声了,今天就来将之前在 Flutter 里...

Day 29-ASP.NET & SQL资料库制作留言板(中)

-前集提要- 要如何把留言的资料(ASP.NET)存到资料库(MSSQL)的留言板。会使用到的工具有...