2017-12-06 14 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}"; 
} 

そして最後に、私はこのようなものだろう:私はこのことについて多くのことをreaded、しかし真剣に、それはそれをこの方法を利用することも可能ですので、いくつかを共有してください場合は何の手掛かりを得なかっ

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

を知識:

+0

これは動作しません。コントローラのアドバイスはコントローラを(基本的に)包み込み、例外を処理します。コントローラはコントローラに戻されません。 –

+0

あなたは私の問題をどのように解決することができますか? ExceptionHandlerはどこに置くべきですか? – degath

+0

コントローラーのアドバイスが自動的に適用されます... –

答えて

0

これは私の例外を処理する方法です。あなたの質問には答えられないかもしれませんが、私はあなたにヒントを与えることを願っています:

私はクラスProductsFoundUnderCategoryExceptionを持っています。

@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"; 
      } 

結果:私の次のようにコントローラが見える中で、今

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; 
    } 

: 私はそれに次のコードを追加しまし

enter image description here

@ResponseStatus注釈。私の場合、私は (org.springframework.http.HttpStatus)を設定しました。これはおなじみのHTTP 404 の応答を示しています。 2番目の属性reasonは、HTTP応答エラーに使用される理由を示します。

+0

私にとっては間違いないヒントですが、私の場合は別のページ(たとえばhttpステータス404)にアクセスするのではなく、もう一度フォームに戻ってもう一度入力したいと思っています。クイックブレーク後、私はあなたの答えを、本当にありがとう、私の状態で解決するように修正しようとします:) – degath

+0

私はあなたが404ページの代わりにすべてを再び満たすためにフォームに戻ることを知っていますが、今は時間がありません。私は確認して戻ってくる。 –

+0

私はそれを自分で処理しようとします、とにかく感謝:) – degath

関連する問題