iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Modern Web

關於我快30歲的後端工程師,想轉職成全端工程師,在前端世界中尋求機會的那件事(後端篇)系列 第 17

[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。


上一篇
[Day 16]新試劑服英戰士(後端篇)
下一篇
[Day 18]所以我說那個醬汁呢(後端篇)
系列文
關於我快30歲的後端工程師,想轉職成全端工程師,在前端世界中尋求機會的那件事(後端篇)18
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言