Exception 처리 Dynamic Error Pages 만들기 - eunja511005/Tutorial GitHub Wiki

Exception 클래스 만들기

import com.eun.tutorial.dto.Book;

import lombok.Getter;

@Getter
public class DuplicateBookException extends RuntimeException {
    private final Book book;

    public DuplicateBookException(Book book) {
        this.book = book;
    }
}
}


addBook 호출시 오류 나도록 수정

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.stereotype.Service;

import com.eun.tutorial.dto.Book;
import com.eun.tutorial.exception.DuplicateBookException;
import com.eun.tutorial.util.StringUtils;

@Service
public class BookServiceImpl implements BookService {

	@Override
	public Collection<Book> getBooks() {
		List<Book> bookList = new ArrayList<Book>();
		Book book1 = Book.builder().isbn("isbn1").name("name1").author("author1").build();
		Book book2 = Book.builder().isbn("isbn2").name("name2").author("author2").build();
		bookList.add(book1);
		bookList.add(book2);
		return bookList;
	}

	@Override
	public Book addBook(Book book) {
		if (StringUtils.isBlank(book.getIsbn())) {
			throw new DuplicateBookException(book);
		}
		return null;
	}

}


ControllerAdvisor 추가

package com.eun.tutorial.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class LibraryControllerAdvice {

    @ExceptionHandler(value = DuplicateBookException.class)
    public ModelAndView duplicateBookException(DuplicateBookException e) {
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("ref", e.getBook().getIsbn());
        modelAndView.addObject("object", e.getBook());
        modelAndView.addObject("message", "Cannot add an already existing book");
        modelAndView.setViewName("error-book");
        return modelAndView;
    }
}


Error jsp 페이지 추가

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Error</title>
    </head>
    <body>
        <p>Reference: ${ref}</p>
        <p>Error Message: ${message}</p>
        <p>Object: ${object}</p>
    </body>
</html>


확인

http://localhost:8080/book/addBook

image

REST 방식 오류 리턴

package com.sec.api.common.code;

public enum CustomExceptionResponse {
    EXCEED_MAX_SIZE(1001, "PARSING_COMPLETED"),
    NOT_SUPPORT_MIMETYPE(1002, "The mime-type of the attached file is not supported.");

    private Integer returnCd;
    private String returnMsg;

    CustomExceptionResponse(int returnCd, String returnMsg){
        this.returnCd=returnCd;
        this.returnMsg=returnMsg;
    }

    public int getReturnCode(){
        return returnCd;
    }

    public String getReturnMsg(){
        return returnMsg;
    }
}

package com.sec.api.exception;

import com.sec.api.common.code.CustomExceptionResponse;

public class CustomException extends Exception {
    private int returnCode = -1;
    private Exception exception = null;

    public CustomException(CustomExceptionResponse customExceptionResponse, Exception e) {
        super(customExceptionResponse.getReturnMsg(), e);
        this.returnCode = customExceptionResponse.getReturnCode();
        this.exception = e;
    }

    public int getReturnCode(){
        return returnCode;
    }

    public Exception getException(){
        return exception;
    }
}

package com.sec.api.exception;

import com.sec.api.common.code.ErrorCode;
import com.sec.api.message.ResponseMessage;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@ControllerAdvice
@AllArgsConstructor
public class GlobalExceptionHandler {

//    private final ZthmErrorService zthmErrorService;

//    @ExceptionHandler(Exception.class)
//    public ResponseEntity<ErrorResponse> handleException(Exception ex){
//        log.error("handleException",ex);
//;
//        zthmErrorService.save(ZthmError.builder()
//                                .errorMessage("GlobalExceptionHandler Error : " + ex.getMessage())
//                                .build()
//        );
//        ErrorResponse response = new ErrorResponse(ErrorCode.INTER_SERVER_ERROR);
//        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
//    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<ResponseMessage> handleMaxSizeException(MaxUploadSizeExceededException exc) {
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(5001,"File too large!"));
    }

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<ResponseMessage> handleCustomException(CustomException e) {
        log.error("handleException",e);
        return ResponseEntity
                .status(HttpStatus.OK)
                .body(new ResponseMessage(e.getReturnCode(), e.getException().getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception ex){
        log.error("handleException",ex);
        ErrorResponse response = new ErrorResponse(ErrorCode.INTER_SERVER_ERROR);
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

⚠️ **GitHub.com Fallback** ⚠️