2017-12-06 7 views
0

글로벌 기본 예외 핸들러를 만들었으며 컨트롤러에서이 글로벌 캐치를 사용하려고합니다.예외 핸들러

@ControllerAdvice 
class GlobalDefaultExceptionHandler { 
    public static final String DEFAULT_ERROR_VIEW = "error"; 

    @ResponseStatus(value= HttpStatus.CONFLICT, 
     reason="Data integrity violation") 
    @ExceptionHandler(DataIntegrityViolationException.class) 
    public void dataIntegrityViolationException() { 
     //do nothing, because I want just catch it 
     //and make use of it in controller. 
    } 
} 

이것은이 오류를 사용하려는 나의 컨트롤러 방법입니다. 이 같은

@PostMapping("/add") 
public String addTask(@Valid BasicForm basicForm, BindingResult result, RedirectAttributes redirectAttrs) { 
    if (result.hasErrors()) { 
     redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.basicForm", result); 
     redirectAttrs.addFlashAttribute("basicForm", basicForm); 
     return "user-add-page"; 
    } 

    taskService.add(basicForm); 

    redirectAttrs.addAttribute("id", basicForm.getId()); 
    return "redirect:/user/{id}"; 
} 

그리고 마지막으로 내가 할 무언가 :

 if (result.hasErrors() || dataIntegrityViolationException()) { 

나는 이것에 대해 많이 읽혀질 수 있지만, 그래서 일부를이 방법을 공유하시기 바랍니다 그것을 활용하는 경우에도 가능하다면 심각 단서 없어 지식 :)

+0

그게 어떻게 작동하지 않습니다 ... 컨트롤러 조언 (기본적으로) 컨트롤러 주위에 래핑하고 예외를 처리 할, 컨트롤을 다시 컨트롤러로 전달되지 않습니다. –

+0

내 문제를 어떻게 해결할 수 있는지 실감을 줄 수 있습니까? ExceptionHandler는 어디에 두어야합니까? – degath

+0

컨트롤러에 대한 조언이 자동으로 적용됩니다 ... –

답변

0

이것은 내 예외를 처리하는 방법입니다. 귀하의 질문에 대답하지 않을 수 있습니다하지만 희망은 당신에게 힌트를주지 희망 :

나는 ProductsFoundUnderCategoryException 클래스가 있습니다. 나는 그것으로 추가 한 다음 코드를했습니다는 :

import org.springframework.http.HttpStatus; 
    import org.springframework.web.bind.annotation.ResponseStatus; 

    @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No products found under this category") 
public class ProductsFoundUnderCategoryException extends RuntimeException{ 
    private static final long serialVersionUID =3935230281455340039L; 
    } 

이제 내 컨트롤러에 다음과 같습니다

@RequestMapping("/{category}") 
public String getProductsByCategory(Model model,@PathVariable("category") String category) { 
List<Product> products =productService.getProductsByCategory(category); 
if (products == null || products.isEmpty()) { 
    throw new NoProductsFoundUnderCategoryException(); 
    } 
    model.addAttribute("products", products); 
      return "products"; 
      } 

결과 :

enter image description here

@ResponseStatus 주석; 제 경우에는 HttpStatus.NOT_FOUND (org.springframework.http.HttpStatus)으로 구성되어 익숙한 HTTP 404 응답을 나타냅니다. 두 번째 속성 인 reason은 HTTP 응답 오류에 사용할 이유를 나타냅니다.

+0

분명히 나에게 좋은 힌트지만, 내 경우는 다른 페이지 (예 : http 상태 404)를 얻는 것이 아니며, 모두 다시 채우기 위해 양식으로 돌아가고 싶습니다.빠른 휴식 후에 나는 내 조건에 대한 답변을 고쳐 주겠다. 정말로 감사한다. – degath

+0

나는 404 페이지 대신에 모두 다시 채우기 위해 양식으로 돌아가고 싶지만 지금은 시간이 없다. 나는 확인하고 돌아올거야. –

+0

나는 그것을 내 자신으로 처리하려고합니다, 어쨌든 감사합니다 :) – degath