오류 메시지 표시하기

By | 2020년 3월 22일
Table of Contents

오류 메시지 표시하기

@Controller 에서 오류 메시지 표시하기

@RequiredArgsConstructor
@Controller
public class IndexController {

    // ......

    @GetMapping("/posts/update/{id:[0-9]+}")
    public String postsUpdate(@PathVariable Long id, Model model) {
        try {
            PostsResponseDto dto = postsService.findById(id);
            model.addAttribute("post", dto);

            return "posts-update";
        } catch (IllegalArgumentException ex) {
            model.addAttribute("message", ex.getMessage());

            return "error/alert_and_back";
        }
    }
}

IllegalArgumentException 에러가 발생할 시 error/alert_and_back 페이지를 표시합니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Error</title>
</head>
<body>
<script>alert('[[${message}]]'); history.back();</script>
</body>
</html>

message 로 전달된 오류 메시지가 표시됩니다.

@RestController 에서 오류 메시지 표시하기

@RequiredArgsConstructor
@RestController
public class PostsApiController {

    // ......

    @DeleteMapping("/api/v1/posts/{id}")
    public Long delete(@PathVariable Long id) {
        postsService.delete(id);
        return id;
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public String exceptionHandler(IllegalArgumentException ex){
        return ex.getMessage();
    }
}

@ExceptionHandler 를 오류처리를 위한 메소드에 추가합니다.

    delete : function() {
        var id = $('#id').val();

        $.ajax({
            type : 'DELETE',
            url : '/api/v1/posts/' + id,
            dataType : 'json',
            contentType : 'application/json; charset=utf-8'
        }).done(function() {
            alert('글이 삭제되었습니다.');
            window.location.href = '/';
        }).fail(function(error) {
            // console.log(JSON.stringify(error));
            if (error.status == 200) {
                alert(error.responseText);
            } else {
                alert('알 수 없는 오류입니다.');
            }
        });
    }

error.responseText 에서 오류 메시지를 확인할 수 있습니다.

답글 남기기