核心接口
HandlerExceptionResolver
实现类
SimpleMappingExceptionResolver
DefaultHandlerExceptionResolver
ResponseStatusExceptionResolver --顾名思义处理标记了 ResponseStatus的注解的方法或类
ExceptionHandlerExceptionResolver
异常处理方法
@ExceptionHandler
添加位置(advice优先级低)
@Controller/@RestController
@ControllerAdvice/@RestControllerAdvice
Controller
@PostMapping(path = "/getException",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Coffee getException(@RequestBody @Valid Coffee coffee,BindingResult result){
if(result.hasErrors()){
throw new ValidationException(result.toString());
}
return coffee;
}
RestControllerAdvice
package com.example.ribi.controller;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalControllerAdvice {
@ExceptionHandler(ValidationException.class) //指定要处理哪一个异常类
@ResponseStatus(HttpStatus.BAD_REQUEST) //指定要返回那种状态码
public Map<String,String> validationExceptionHandler(ValidationException exception){
Map<String,String> map = new HashMap<>();
map.put("message",exception.getMessage());
return map;
}
}
Test
Post localhost:8080/user/getException raw {"name":"coffee","money":12}
{
"name": "coffee",
"money": 12
}
Post localhost:8080/user/getException raw {"money":12}
{
"message": "org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object 'coffee' on field 'name': rejected value [null]; codes [NotEmpty.coffee.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [coffee.name,name]; arguments []; default message [name]]; default message [不能为空]"
}
--部分摘自极客时间玩转spring全家桶