Skip to content

spring boot error code specification with swagger example

Notifications You must be signed in to change notification settings

pjh612/swagger-error-spec-example

Repository files navigation

springdoc:
    info:
        title: ${spring.application.name}
        description: ${spring.application.name} docs for ${spring.profiles.active}
        contact:
            name: Jinhyung Park
            email: pjh_jn@naver.com
            url: https://github.com/pjh612/swagger-error-spec-example

image

@RestController
public class SampleController {

    @ApiErrorCodeExample(
            examples = {
                    @ExceptionCodeExample(title = "비밀번호 틀릴 때", codes = {"C-001"}),
                    @ExceptionCodeExample(title = "입력한 아이디가 존재하지 않을 때", codes = {"C-002"})}
    )
    @GetMapping("/sample")
    public String sample(@RequestBody SampleRequest request) {
        return request.toString();
    }
}

image

아래와 같이 ExceptionHandler를 작성해 응답 형식 통일

@RestControllerAdvice
public class GlobalExceptionHandler {
    private final ExceptionCodeConverter exceptionCodeConverter;

    public GlobalExceptionHandler(ExceptionCodeConverter exceptionCodeConverter) {
        this.exceptionCodeConverter = exceptionCodeConverter;
    }

    @ExceptionHandler(BusinessException.class)
    public ExceptionResponse handleBusinessException(BusinessException e) {
        StatusException[] errors = exceptionCodeConverter.toError(e.getExceptionContent()
                .stream()
                .map(ExceptionContent::getCode)
                .toArray(String[]::new));

        return exceptionCodeConverter.toExceptionResponse(errors);
    }
}

About

spring boot error code specification with swagger example

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages