leyou_01_ custom exception handler

1. Custom exception handler when an exception occurs can program we can define their own return status code and status information

2. Call our custom exception when an exception occurs

@RestController
@RequestMapping("item")
public class ItemController {
    @Autowired
    private ItemService itemService;

    @PostMapping
    public ResponseEntity<Item> saveItem(Item item) {
        //检验价格是否为空
        if(item.getPrice()==null){
            throw new LyException(ExceptionEnum.PRICE_CANNOT_BE_NULL);//自定义异常LyException
           // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
         item = itemService.saveItem(item);
        return ResponseEntity.status(HttpStatus.CREATED).body(item);
    }
}

 

Description: the throw new new LyException (ExceptionEnum.PRICE_CANNOT_BE_NULL); // custom exception LyException

LyException () need to pass a custom exception ExceptionEnum object contains status codes, and error messages

Status and error codes to prevent the image of misinformation can be written to enumerate the form

ExceptionEnum.class

@Getter 
@NoArgsConstructor 
@AllArgsConstructor 
public  enum ExceptionEnum { 

    PRICE_CANNOT_BE_NULL ( 400, "price can not be empty!" ), 
    ; 
    Private  int code;
     Private String MSG; 
}

 

 

SpringMvc intercepted abnormal

/ ** 
 * Universal exception handler 
 * / 
@ControllerAdvice // default to block all 
public  class CommonExceptionHandle {
     // the return value of the method is to return the page stuff
     // catch the exception 
    @ExceptionHandler (LyException. Class )
     public ResponseEntity <ExceptionResult> handleException (LyException E) { 
        ExceptionEnum EM = e.getExceptionEnum ();
         return ResponseEntity.status (em.getCode ()) body (. new new ExceptionResult (e.getExceptionEnum ())); 

    } 
}

 

 

Dispensing exception return a result set

/**
 * 封装一个异常处理信息的返回结果集
 */
@Data
public class ExceptionResult {
    private int status;
    private String message;
    private Long timestamp;

    public ExceptionResult(ExceptionEnum em) {
        this.status=em.getCode();
        this.message=em.getMsg();
        this.timestamp=System.currentTimeMillis();
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/asndxj/p/11536453.html