controlleradvice类
1. 使用该注解 , 该注解标识的类会获取并修改controller中爆出的相应异常.
package com.imooc.demo.exception;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(value = MyException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Map<String,Object> handlerUserNotExistException(MyException m) {
Map<String ,Object> map = new HashMap<>();
map.put("id",m.getId());
map.put("message",m.getMessage());
return map;
}
// 该方法无效 , 待修改
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody
public Map<String,Object> handlerValidExistException(BindingResult result) {
Map<String ,Object> map = new HashMap<>();
if (result != null) {
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
for (int i = 0; i < errors.size(); i++) {
map.put(Integer.toString(i),errors.get(i).getObjectName());
}
}
} else {
map.put("field","result is null");
}
return map;
}
}
- controller异常类
package com.imooc.demo;
import com.imooc.demo.exception.MyException;
import com.imooc.demo.security.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
@PostMapping("")
public String hello() {
// return "success";
throw new MyException("12","haha");
// return "hello";
}
}
- 自定义异常类
package com.imooc.demo.exception;
public class MyException extends RuntimeException{
private String id;
public MyException(String id,String message) {
super(message);
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
- 请求url
http://localhost:8080/
- 报错信息
{
"id": "12",
"message": "haha"
}